简体   繁体   English

如何使用Java执行多个SQL语句?

[英]How to execute multiple SQL statement using Java?

I have a batch process program in place where I am using JDBC to make calls to the database. 我有一个批处理程序,我正在使用JDBC来调用数据库。 I am sending information in a batch of 100 with 'ID' as the primary key. 我将以100个批次发送信息,并以“ID”作为主键。

I want to make a single call to the database and then execute multiple SQL statements before closing the connection. 我想对数据库进行一次调用,然后在关闭连接之前执行多个SQL语句。

I am posting portion of the code for reference 我发布了部分代码供参考

        //  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

I want to do three things in one go for each ID in the for loop. 我想在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
}

How to execute all the statements without having to close the connection for each ID? 如何执行所有语句而不必关闭每个ID的连接? New to JDBC and SQL. JDBC和SQL新手。 Any help is appreciated. 任何帮助表示赞赏。

Okay so there are many problems with your code. 好吧,你的代码有很多问题。 First off, 首先,

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

You would have to pass a Driver implementation, not the interface itself; 你必须传递一个Driver实现,而不是接口本身; but the good news is that this code is unnecessary as of JDBC 4.0. 但好消息是,从JDBC 4.0开始,此代码是不必要的。 It already scans your classpath to locate drivers for you. 它已经扫描了您的类路径以找到适合您的驱动程序。

Second, your connection is not being closed with each query. 其次,每次查询都不会关闭您的连接。 There's nowhere in your code where you're calling connec.close() . 您的代码中没有任何地方可以调用connec.close() JDBC won't close the connection for you, either. JDBC也不会为您关闭连接。

Third, you don't need to do this with nested for loops! 第三,你不需要使用嵌套的for循环来做这件事! That is an awful idea. 这是一个糟糕的主意。 Your concept of SQL queries and JDBC needs some sharpening. 您的SQL查询和JDBC概念需要一些锐化。 You can simply do the following: 您可以简单地执行以下操作:

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

Even better would be to do a batch query. 更好的是进行批量查询。

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

It seems you are doing a preliminary round of queries to "check" whether each ID is in the table, but this is not necessary. 您似乎正在进行一轮初步查询以“检查”每个ID是否在表中,但这不是必需的。 If the ID is not in the table, then you'll get an empty result set in return. 如果ID不在表中,那么您将得到一个空的结果集作为回报。 There's nothing wrong with an empty result set. 空结果集没有任何问题。 Your while loop will never run in this case because rs.next() will return false. 在这种情况下,你的while循环永远不会运行,因为rs.next()将返回false。 You can also check whether it's empty by calling rs.first() . 您还可以通过调用rs.first()来检查它是否为空。 This way doesn't move the cursor. 这种方式不会移动光标。

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

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