最近在优化一个老项目的代码,处理数据库连接部分发现这样几行语句。
public ResultSet openRs(String sql) throws SQLException
{
Statement sqlStatement1 = this.dbCon.createStatement(1005, 1008);
ResultSet rs = sqlStatement1.executeQuery(sql);
return rs;
}
当时想每次执行sql都要创建sqlstatement多浪费啊,于是就改掉了,变成全局对象,结果报错了。
后来认真查阅了下API,原来sqlstatement与ResultSet是终生一对一的爱情,不是一对多的滥情,好专一啊。
* By default, only one <code>ResultSet</code> object per <code>Statement</code>
* object can be open at the same time. Therefore, if the reading of one
* <code>ResultSet</code> object is interleaved
* with the reading of another, each must have been generated by
* different <code>Statement</code> objects. All execution methods in the
* <code>Statement</code> interface implicitly close a statment's current
* <code>ResultSet</code> object if an open one exists.
*