0

I am using Java (JDBC) to create a command line utility for SQL statement execution. A script is defined as a text file, having many queries. Each query is separated by a query separator (";"). The output is routed to stdout.

SELECT * FROM table1;
UPDATE table1 SET field1='' WHERE field2='';
SELECT * FROM table1;
INSERT INTO table1 VALUES(...)
SELECT * FROM table1;

Since JDBC can execute statements batchwise, only if they don't return a ResultSet, I need another approach.

As of now, I would read the script file with the queries, split them by the separator, and analyze each query, whether it's a "SELECT" query, or an "INSERT", "UPDATE", "DELETE" query. After that, I would execute each query in it's own statement. The ones that return something are written to stdout, the queries that manipulate the database are executed. And, of course I would keep the order of the queries from the file.

My problem is: If one of the queries in the file is wrong, I can't rollback, because each query is executed separately. How could I handle this issue?

Kiril
  • 6,009
  • 13
  • 57
  • 77

3 Answers3

1

For your database connection, just call connection.setAutoCommit(false) then execute your statements and call connection.commit() when you're finished, or connection.rollback() if you encounter an error.

BarrySW19
  • 3,759
  • 12
  • 26
  • For details see the Java Tutorial on [Transactions](http://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html). – Gord Thompson Oct 21 '14 at 10:00
  • The main problem is the differentiation between `SELECT` queries and `UPDATE, DELETE, INSERT...`. This answer has it covered, i think: http://stackoverflow.com/a/1497614/1188357 – Kiril Oct 21 '14 at 11:10
1

This is the code for for adding queries to batch.

Statement stmt = conn.createStatement();
conn.setAutoCommit(false);

String SQL = "INSERT INTO table1 VALUES(...)";
stmt.addBatch(SQL);

String SQL = "INSERT INTO Employees (id, first, last, age) " +
         "VALUES(201,'Raj', 'Kumar', 35)";
stmt.addBatch(SQL);

String SQL = "UPDATE Employees SET age = 35 " +
         "WHERE id = 100";
stmt.addBatch(SQL);


 int[] count = stmt.executeBatch();

//Explicitly commit statements to apply changes

 conn.commit();

Try this.....

Madhavi Talla
  • 205
  • 2
  • 5
  • 12
0

This code might helpful to you.

 String Query1 = "SELECT * FROM Tablename1";
        stmt1 = con.createStatement();
        ResultSet rs = stmt1.executeQuery(Query1);
        rs.next();
        int totalQuery1Count = rs.getInt("TOTAL_Item");

    String Query2 = "SELECT * FROM Tablename2";
        rs = stmt1.executeQuery(Query2);
        rs.next();
        int totalQuery2Count = rs.getInt("TOTAL_Item2");
Peter
  • 855
  • 2
  • 15
  • 35