Question
Is it possible to execute multiple SQL queries in a single statement using JDBC?
"SELECT * FROM TABLE; INSERT INTO TABLE..."
Answer
Executing multiple SQL queries in one statement using JDBC is not supported directly due to the underlying database driver constraints. However, you can achieve similar functionality through other approaches.
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "databaseinjection";
String driver = "com.mysql.jdbc.Driver";
String sqlUsername = "root";
String sqlPassword = "abc";
// Load the driver
Class.forName(driver);
// Establish the connection
connection = DriverManager.getConnection(url+dbName, sqlUsername, sqlPassword);
statement = connection.createStatement();
// Split and execute multiple statements
statement.executeUpdate("INSERT INTO TABLE_NAME (column1) VALUES ('value1')");
ResultSet rs = statement.executeQuery("SELECT * FROM TABLE_NAME");
while (rs.next()) {
System.out.println(rs.getString("column1"));
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try { if (statement != null) statement.close(); }
catch (SQLException e) { e.printStackTrace(); }
try { if (connection != null) connection.close(); }
catch (SQLException e) { e.printStackTrace(); }
}
}
}
Causes
- JDBC does not allow executing multiple SQL statements at once due to security risks like SQL injection.
- Database drivers typically parse and execute only one statement at a time.
Solutions
- Use batch processing to execute multiple statements in a single batch using `PreparedStatement`.
- Split the SQL string into separate statements and execute them individually.
Common Mistakes
Mistake: Trying to execute raw SQL strings with multiple statements without separating them.
Solution: Always execute statements one at a time or use batch processing.
Mistake: Not handling SQL exception properly.
Solution: Implement adequate exception handling to catch and handle SQL or connection errors.
Helpers
- JDBC
- execute multiple SQL queries
- Java database connection
- MySQL JDBC
- JDBC statement execution