try {
Connection conn = ...;
Statement stmt = ...;
ResultSet rs = stmt.executeQuery("select * from table1");
while(rs.next()) {
}
} catch(Exception ex) {
}
这段代码有什么不足之处?
Connection conn = ...;
Statement stmt = ...;
ResultSet rs = stmt.executeQuery("select * from table1");
while(rs.next()) {
}
} catch(Exception ex) {
}
这段代码有什么不足之处?
Connection conn = ...;
Statement stmt = ...;
ResultSet rs = stmt.executeQuery("select * from table1");
while(rs.next()) {
}
} catch(Exception ex) {
} finally{
rs.close();
stmt.clost();
conn.close();
}是不是用了以后要关闭呀.
Statement 不支持预编译
一般使用PreParedStatement 要好点点。
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = ...;
String sql = "SELECT id, name, password FROM user WHERE name = ? AND password = ?";
ps = con.prepareStatement(sql);
ps.setString(1, "name");
ps.setString(2, "pwd");
rs = ps.executeQuery();
while(rs.next()) {
...
}
} catch(Exception ex) {
log.error(e.getMessage());
throw new MyDbException(e);
} finally {
if(rs != null) {
try {
rs.close();
}catch(SQLException e) {
log.error(e.getMessage());
throw new MyDbException(e);
}
}
// ps 和 con 同样采用 rs 方式进行处理
}MyDbException 是个自定义的 RuntimeException
还是就是数据库是的连接是必须关关闭,不然连接多了会造成内在不够用啊?
还要将异常处理掉或者抛出啊!!!!
try {
Connection conn = ...;
Statement stmt = ...;
ResultSet rs = stmt.executeQuery("select * from table1");
while(rs.next()) {
}
} catch(Exception ex) { } finally{
if (rs!=null) {
try {
rs.close();
}catch(SQLException e) {
e.printStackTrace(); }
}
if (stmt!=null) {
try {
stmt.clost();
}catch(SQLException e) {
e.printStackTrace(); }
}if (conn!=null) {
try {
conn.close();
}catch(SQLException e) {
e.printStackTrace(); }
}
}