我想知道是否可以使用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执行类似的操作。
对的,这是可能的。据我所知,有两种方法。他们是
示例1:(允许多个查询):
发送连接请求时,你需要将连接属性附加allowMultiQueries=true到数据库URL。这是额外的连接属性,如果那些已经存在的一些,比如autoReConnect=true,对等。可接受的值allowMultiQueries属性是true,false,yes,和no。其他任何值在运行时都使用拒绝SQLException。
allowMultiQueries=true
autoReConnect=true
allowMultiQueries
true
false
yes
no
SQLException
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
除非传递了此类指令,否则SQLException将引发an 。
你必须使用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
ResultSet
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