0 0

jdbc PreparedStatement executeBatch方法执行效率低的问题10

我知道PreparedStatement可以一次执行多条sql语句。通过addBatch方法添加sql,最后执行。
我的代码如下(就是一个循环,每次添加一条sql,最后执行。但是不知为什么,很耗时):
public void writeToDB(ArrayList<Item> wordList)
    {
        int i = 0,
            size = 0;
        Item item = null;
        Connection conn = null;
        PreparedStatement pStmt = null;
        String sql = "insert into t_item(word,trans,phonetic,difficulty) values(?,?,?,?)";
        
        size = wordList.size();
        conn = DB.getConn();
        pStmt = DB.getpStmt(conn, sql);

        for(i=0;i<size;i++)
        {
            item = (Item) wordList.get(i);
            try {
                pStmt.setString(1, item.getWord());
                pStmt.setString(2, item.getTrans());
                pStmt.setString(3, item.getPhonetic());
                pStmt.setInt(4, item.getDifficulty());
                pStmt.addBatch();
            } catch (SQLException e) {
                e.printStackTrace();
                continue;
            }
        }

        try {
            pStmt.executeBatch();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


wordList里一共有800多个条目
我用ystem.currentTimeMillis()方法测得 for循环体执行时间大概是25毫秒,但是pStmt.executeBatch()这一条语句要22841毫秒!!!应该一共只有800多个sql语句啊。。。不知道为什么会用这么长时间。。。

个位大侠,有什么解决方案吗?是我的代码有问题,还是现实就是这么残酷?。。。
除了写存储过程,还有其他办法吗?

学习中,多谢!

问题补充:
pacer123 写道
for(i=0;i<size;i++)  
        {  
            item = (Item) wordList.get(i);  
            try {  
                pStmt.setString(1, item.getWord());  
                pStmt.setString(2, item.getTrans());  
                pStmt.setString(3, item.getPhonetic());  
                pStmt.setInt(4, item.getDifficulty());  
                pStmt.addBatch();  
                //增加如下2行代码试试
                    if(i%200==0)
                   {pStmt.executeBatch(); }
            } catch (SQLException e) {  
                e.printStackTrace();  
                continue;  
            }  
        }  


谢谢啊,已经解决了~
问题是事务提交没有设成手动的,导致每执行一次sql语句,就会提交一次事务,时间都浪费在这里了。
应该
conn.setAutoCommit(false);
......
conn.commit();
DAO 
2011年6月17日 08:20

1个答案 按时间排序 按投票排序

0 0

for(i=0;i<size;i++)  
        {  
            item = (Item) wordList.get(i);  
            try {  
                pStmt.setString(1, item.getWord());  
                pStmt.setString(2, item.getTrans());  
                pStmt.setString(3, item.getPhonetic());  
                pStmt.setInt(4, item.getDifficulty());  
                pStmt.addBatch();  
                //增加如下2行代码试试
                    if(i%200==0)
                   {pStmt.executeBatch(); }
            } catch (SQLException e) {  
                e.printStackTrace();  
                continue;  
            }  
        }  

2011年6月20日 11:51

相关推荐

Global site tag (gtag.js) - Google Analytics