这里提供的写法并未使用连接池和工具类,只是对纯原始写法的一点探索,供大家参考。
public String testFormat(String date) //获取当天的身份证号
{
String result = null;
Connection conn = DriverManager.getConnection("jdbc:mysql://host:port/datebase","user","password");
ResultSet rs = null;
if(conn!=null)
{
try{
//省略具体的数据库操作
}
catch (Exception e) {
e.printStackTrace();
}
finally {
/**
* 先判断resultset和connection是否为空,不为空则需要关闭
* try关闭,catch异常
* 最终给resultset和connection赋值为空,告诉gc不再需要,交给垃圾回收机制去处理
*/
if(rs!=null)
{
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs=null;
}
if(conn!=null)
{
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
}
return result;
}