简体   繁体   English

使用MySQL连接器Java改善查询

[英]Improve query with MySQL connector Java

When I have to deal with MySQL DB in Java, I use the driver developed by MySQL itself. 当我不得不用Java处理MySQL DB时,我使用MySQL本身开发的驱动程序。 It is very easy to work with this library but I have a question about performance. 使用该库非常容易,但是我对性能有疑问。 What "closing" method should I use each time I make a query to a DB? 每次查询数据库时,应使用哪种“关闭”方法?

If for example I have a for loop, which makes more inserts in DB, what should I use ? 例如,如果我有一个for循环,该循环在DB中进行了更多插入,那我应该使用什么?

private void invioInsert(String query){
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception E) {
        System.err.println("Non trovo il driver da caricare.");
        E.printStackTrace();
    }
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.execute();
        statement.close();

    } catch (SQLException E) {
        System.out.println("SQLException: " + E.getMessage());
        System.out.println("SQLState:     " + E.getSQLState());
        System.out.println("VendorError:  " + E.getErrorCode());
    }
}

For example the for loop can be: 例如,for循环可以是:

for(int i=0; i<=10, i++){
    String query = "INSERT TABLE VALUES ("+i+")";
    sendQuery(query);
}

So this is the complete code of for loop: 因此,这是for循环的完整代码:

for (int i = 0; i < file.getList().size(); i++) {
        StringTokenizer tokenizer = new StringTokenizer(file.getList().get(i).replace("\"", ""));
        String ID = tokenizer.nextToken("|");
        int j = 0;
        while(j<5){
            tokenizer.nextToken("|");
            j++;
        }
        String voto = tokenizer.nextToken("|");
        String query = "Insert RisultatiGiocatori values ('"+giornata+"','"+ID+"','"+voto+"')";
        invioInsert(query);
    }

This is a classic usecase for a PreparedStatement with batch execution: 这是带有批处理执行的PreparedStatement的经典用例:

String query = "INSERT TABLE VALUES (?)";
try {
    PreparedStatement statement = conn.prepareStatement(query);
    for(int i=0; i<=10, i++){
        statement.setInt(1, i);
        statement.addBatch();
    }
    statement.executeBatch();
    statement.close();

} catch (SQLException E) {
    System.out.println("SQLException: " + E.getMessage());
    System.out.println("SQLState:     " + E.getSQLState());
    System.out.println("VendorError:  " + E.getErrorCode());
}

Never create a PreparedStatement inside loops. 切勿在循环内创建PreparedStatement。 Try to create the statement outside and you'll have a great improvement. 尝试在外部创建语句,将会有很大的改进。

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

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