简体   繁体   English

使用JDBC执行多个SQL语句(CRUD)

[英]Execute multiple SQL statements (CRUD) with JDBC

I am using Java (JDBC) to create a command line utility for SQL statement execution. 我正在使用Java(JDBC)创建用于SQL语句执行的命令行实用程序。 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. 由于JDBC可以批量执行语句,因此仅当它们不返回ResultSet时,我需要另一种方法。

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. 到目前为止,我将读取包含查询的脚本文件,使用分隔符对其进行拆分,然后分析每个查询,无论是“ SELECT”查询还是“ INSERT”,“ UPDATE”,“ DELETE”查询。 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. 将返回内容的内容写入stdout,并执行操纵数据库的查询。 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? 我该如何处理?

对于数据库连接,只需调用connection.setAutoCommit(false)然后执行语句,并在完成时调用connection.commit()即可;如果遇到错误,则可以调用connection.rollback()。

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..... 尝试这个.....

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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM