Hi I was wondering if it is possible to execute something like this using JDBC as it currently provides an exception even though it is possible in the MySQL query browser.
"SELECT FROM * TABLE;INSERT INTO TABLE;"
While I do realize that it is possible with having the SQL query string being split and the statement executed twice but I was wondering if there is a one time approach for this.
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);
Why dont you try and write a
Stored Procedure
for this?You can get the
Result Set
out and in the sameStored Procedure
you canInsert
what you want.The only thing is you might not get the newly inserted rows in the
Result Set
if youInsert
after theSelect
.I think this is the easiest way for multy selection/update/insert/delete. You can run as many update/insert/delete as u want after select (you have to make a select first(a dummy if needed)) with executeUpdate(str) (just use new int(count1,count2,...)) and if u need a new selection close 'statement' and 'connection' and make new for next select. Like example:
I hope it helps
I was wondering if it is possible to execute something like this using JDBC.
Yes it is possible. There are two ways, as far as I know. They are
Following examples demonstrate the above two possibilities.
Example 1: ( To allow multiple queries ):
While sending a connection request, you need to append a connection property
allowMultiQueries=true
to the database url. This is additional connection property to those if already exists some, likeautoReConnect=true
, etc.. Acceptable values forallowMultiQueries
property aretrue
,false
,yes
, andno
. Any other value is rejected at runtime with anSQLException
.Unless such instruction is passed, an
SQLException
is thrown.You have to use
execute( String sql )
or its other variants to fetch results of the query execution.To iterate through and process results you require following steps:
Example 2: Steps to follow:
select
, andDML
queries.CallableStatement
.ResultSet
s executed in procedure.DML results can't be captured but can issue another
select
to find how the rows are affected in the table.
Sample table and procedure:
Call Procedure from Java:
You can use Batch update but queries must be action(i.e. insert,update and delete) queries
Hint: If you have more than one connection property then separate them with:
To give you somthing like:
I hope this helps some one.
Regards,
Glyn
Based on my testing, the correct flag is "allowMultiQueries=true"