嗨,我想知道是否可以使用 JDBC 执行类似的操作,因为它当前提供了一个异常,即使在 MySQL 查询浏览器中是可能的。
"SELECT FROM * TABLE;INSERT INTO TABLE;"
虽然我确实意识到可以拆分 SQL 查询字符串并执行两次语句,但我想知道是否有一种一次性方法。
String url = "jdbc:mysql://localhost:3306/";
String dbName = "databaseinjection";
String driver = "com.mysql.jdbc.Driver";
String sqlUsername = "root";
String sqlPassword = "abc";
Class.forName(driver).newInstance();
connection = DriverManager.getConnection(url+dbName, sqlUsername, sqlPassword);
最佳答案
我想知道是否可以使用 JDBC 执行类似的操作。
"SELECT * FROM TABLE;INSERT INTO TABLE;"
是的,这是可能的。据我所知,有两种方法。他们是
- 通过设置数据库连接属性以允许多个查询, 默认以分号分隔。
- 通过调用隐式返回游标的存储过程。
以下示例演示了上述两种可能性。
示例 1:(允许多个查询):
发送连接请求时,您需要将连接属性 allowMultiQueries=true
附加到数据库 URL。如果已经存在一些连接属性,则这是附加的连接属性,例如 autoReConnect=true
等。allowMultiQueries
属性的可接受值为 true
、假
、是
和否
。任何其他值都会在运行时被 SQLException
拒绝。
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
除非传递这样的指令,否则会抛出SQLException
。
您必须使用execute( String sql )
或其其他变体来获取查询执行的结果。
boolean hasMoreResultSets = stmt.execute( multiQuerySqlString );
要迭代并处理结果,您需要执行以下步骤:
READING_QUERY_RESULTS: // label
while ( hasMoreResultSets || stmt.getUpdateCount() != -1 ) {
if ( hasMoreResultSets ) {
Resultset rs = stmt.getResultSet();
// handle your rs here
} // if has rs
else { // if ddl/dml/...
int queryResult = stmt.getUpdateCount();
if ( queryResult == -1 ) { // no more queries processed
break READING_QUERY_RESULTS;
} // no more queries processed
// handle success, failure, generated keys, etc here
} // if ddl/dml/...
// check to continue in the loop
hasMoreResultSets = stmt.getMoreResults();
} // while results
示例 2:遵循的步骤:
- 创建一个包含一个或多个
select
和DML
查询的过程。 - 使用
CallableStatement
从java调用它。 - 您可以捕获过程中执行的多个
ResultSet
。
无法捕获 DML 结果,但可以发出另一个select
了解表中的行受到的影响。
示例表和过程:
mysql> create table tbl_mq( i int not null auto_increment, name varchar(10), primary key (i) );
Query OK, 0 rows affected (0.16 sec)
mysql> delimiter //
mysql> create procedure multi_query()
-> begin
-> select count(*) as name_count from tbl_mq;
-> insert into tbl_mq( names ) values ( 'ravi' );
-> select last_insert_id();
-> select * from tbl_mq;
-> end;
-> //
Query OK, 0 rows affected (0.02 sec)
mysql> delimiter ;
mysql> call multi_query();
+------------+
| name_count |
+------------+
| 0 |
+------------+
1 row in set (0.00 sec)
+------------------+
| last_insert_id() |
+------------------+
| 3 |
+------------------+
1 row in set (0.00 sec)
+---+------+
| i | name |
+---+------+
| 1 | ravi |
+---+------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
从 Java 调用过程:
CallableStatement cstmt = con.prepareCall( "call multi_query()" );
boolean hasMoreResultSets = cstmt.execute();
READING_QUERY_RESULTS:
while ( hasMoreResultSets ) {
Resultset rs = stmt.getResultSet();
// handle your rs here
} // while has more rs
关于java - 在java中单个语句中执行多个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52445322/