大家好, 我最近在开发一些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]