iteye_12054 2010-07-11 00:17
浏览 542
已采纳

PreparedStatement复用 !!!

大家好, 我最近在开发一些SQLite的应用, 有一些JDBC使用上不清楚的地方, 望专家不吝赐教.

问题1:首先是一个将重复调用向数据库写入的方法, 其中对PreparedStatement的使用我拿不准, 我写了两套如下:

public class ContentPersistence extends Persistence{

    private PreparedStatement statementForPut = null;
    
    private void initStatements() throws SQLException{
            this.statementForPut = super.getDBManager().getConnection().prepareStatement("INSERT INTO `"+DBLabel.TABLE_CONTENT+"`(`"+
                    DBLabel.COLUMN_URL_ID_OF_PAGE_CONTENT+"`,`"+
                    DBLabel.COLUMN_CONTENT_OF_PAGE_CONTENT+"`)VALUES(?,?);");
    }
    
    public ContentPersistence(DBManager dbManager) throws SQLException {
        super(dbManager);
        this.initStatements();
    }
    
    public synchronized void put1(Object content) throws SQLException{
        this.statementForPut.setInt(1, ((Content)content).getUrlId());
        this.statementForPut.setBytes(2, (Content)content).getContent());
        this.statementForPut.executeUpdate();
        this.statementForPut.clearBatch();      //? question 2
        this.statementForPut.clearParameters(); //? question 2
    }

    public synchronized void put2(Object content) throws SQLException{
        PreparedStatement preparedStatement = null;
        try{
            preparedStatement = super.getDBManager().getConnection().prepareStatement("INSERT INTO `"+DBLabel.TABLE_CONTENT+"`(`"+
                    DBLabel.COLUMN_URL_ID_OF_PAGE_CONTENT+"`,`"+
                    DBLabel.COLUMN_CONTENT_OF_PAGE_CONTENT+"`)VALUES(?,?);");
            
            preparedStatement.setInt(1, ((Content)content).getUrlId());
            preparedStatement.setBytes(2, (Content)content).getContent());
                preparedStatement.executeBatch();
        }finally{
            if(preparedStatement != null){
                                preparedStatement.close();
                preparedStatement = null;
            }
        }
    }
}



我在网上看了些例子都如put2()中的方式, 但put1()似乎更合理些, 在这里希望得到专家的证实.



问题2: 上面put1()中, 在执行完一次插入数据后, 调用了
    this.statementForPut.clearBatch(); //? question 2
    this.statementForPut.clearParameters(); //? question 2
对statement进行清理, 请教这么使用对不对,有没有必要?



问题3: 最后请专家指点可以优化的地方, 主要是对资源复用与临时变量清理的部分,避免内存漏洞.


谢谢先![img]/images/smiles/icon_smile.gif" alt="[/img][img]/images/smiles/icon_arrow.gif" alt="[/img]

 

  • 写回答

1条回答 默认 最新

  • book_lxf9501 2010-07-11 08:38
    关注

    put1() 可以
    对statement没有必要清理

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥30 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile