java - Java如何执行多条SQL语句?

标签 java mysql sql sql-server batch-file

我有一个批处理程序,我在其中使用 JDBC 调用数据库。 我以“ID”作为主键,以 100 个为一组发送信息。

我想对数据库进行一次调用,然后在关闭连接之前执行多条 SQL 语句。

我贴出部分代码供引用

        //  Database credentials
        String USER = username;
        String PASS = password;

        Connection connec = null;
        Statement stmt = null;

        //STEP 2: Register JDBC driver
        Class.forName("com.mysql.jdbc.Driver");

        //STEP 3: Open a connection
        System.out.println("Connecting to a selected database...");
        connec = DriverManager.getConnection(DB_URL, USER, PASS);
        System.out.println("Connected database successfully...");

        //STEP 4: Execute a query
        System.out.println("Creating statement...");
        stmt = connec.createStatement();

        // Step 2: To update the database with the new count and the netppe values.

        // Step to know whether the ID is present or not in the database
        for(int i=0;i<identities.length;i++){
        String booleanString = "SELECT 1 FROM cgm_counters WHERE id = "+identities[i];

stmt.execute(booleanString);  
        ResultSet resultSet = stmt.getResultSet(); //result set for records  
        boolean recordFound = resultSet.next(); 
        ResultSet rs = null;
// Retrieve the 'netppe' information.
        if(recordFound){

            String sql =  "SELECT * FROM cgm_counters WHERE id="+identities[i];
            rs = stmt.executeQuery(sql);
            while(rs.next()){
                 //Retrieve by column name
                 double net_ppe  = rs.getDouble("spend");
                 System.out.println("The value of the netppe :"+net_ppe);
            }

}// end of 'If' statement

我想在 for 循环中为每个 ID 一次做三件事。

1 > I want to see whether the ID is present or not in the database
2 > If ID - present
{ 
2 a > retrieve the 'netppe' information for that particular ID
2 b > retrieve the 'count' information for that same ID
2 c> Update the database with the new 'netppe' and 'count' value for the same ID
} else {
Insert the information for the new ID
}

如何在不关闭每个 ID 连接的情况下执行所有语句? JDBC 和 SQL 的新手。感谢您的帮助。

最佳答案

好吧,你的代码有很多问题。首先,

//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

您必须传递驱动程序实现,而不是接口(interface)本身;但好消息是,从 JDBC 4.0 开始,这段代码是不必要的。它已经扫描了您的类路径来为您找到驱动程序。

其次,您的连接不会随着每个查询而关闭。在您调用 connec.close() 的代码中没有任何地方。 JDBC 也不会为您关闭连接。

第三,您不需要使用嵌套的 for 循环来执行此操作!那是个糟糕的主意。您对 SQL 查询和 JDBC 的概念需要加强。您可以简单地执行以下操作:

for(int i=0;i<identities.length;i++) {
    String sql =  "SELECT * FROM cgm_counters WHERE id="+identities[i];
    ResultSet rs = stmt.executeQuery(sql);
    while(rs.next()){
        //Retrieve by column name
        double net_ppe  = rs.getDouble("spend");
        System.out.println("The value of the netppe :"+net_ppe);
    }
}

更好的方法是进行批量查询。

String batch = "(";
for (int i = 0; i < identities.length;i++) {
    if (i < identities.length() - 1) 
        batch += "?, ";
    else 
        batch += "?)"
}

String sql =  "SELECT * FROM cgm_counters WHERE id in " + batch;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
    double net_ppe  = rs.getDouble("spend");
    System.out.println("The value of the netppe :"+net_ppe);
}

您似乎正在进行初步查询以“检查”每个 ID 是否在表中,但这不是必需的。如果 ID 不在表中,那么您将得到一个空结果集作为返回。空结果集没有错。在这种情况下,您的 while 循环将永远不会运行,因为 rs.next() 将返回 false。您还可以通过调用 rs.first() 来检查它是否为空。这种方式不会移动光标。

关于java - Java如何执行多条SQL语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22154150/

相关文章:

java - 多个 session 工厂,一个连接?

php - 捕获错误并在插入到唯一列时继续

mysql - MySQL 到 SQL Server over WAN 的 ETL 机制

sql - 如果不存在,PostgreSQL 创建表

mysql - 基于子查询的SQL查询。检索数据>阈值的交易

java - 通过 intellij hibernate 持久化工具生成模型时关系引用禁用表

java - Proftpd - 上传后的 0kb 文件

java - 当 layoutManager 的 scrollToPositionWithOffset 时项目的 recyclerView 之间空白

c# - 为什么两台服务器上有重复版本但一台发送错误子查询返回超过 1 个值

mysql - 考虑参数子集的选择