package com.myselect;
import java.sql.*;
import java.sql.DriverManager;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DataAccess {
Connection conn;
PreparedStatement pst;
ResultSet rs;
public DataAccess() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/db", "root", "root");
} catch (ClassNotFoundException ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String getAge(String name) {
String userage = null;
try {
pst = conn.prepareStatement("select age from mydb where name= ?");
pst.setString(1, name);
rs = pst.executeQuery();
while (rs.next()) {
userage = rs.getString("age");
System.out.println(userage);
}
} catch (Exception ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
return userage;
}
public int insertRecord(String name, int addage) {
int b = 0;
try {
pst = conn.prepareStatement("insert into mydb values(?,?)");
pst.setString(1, name);
pst.setInt(2, addage);
b = pst.executeUpdate();
} catch (Exception ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
return b;
}
}
我想关闭连接.我有几个servlet调用insertRecord和getAge方法.什么是关闭我的连接的最佳方法?创建另一个方法并从insertRecord和getAge方法或构造函数中调用?
解决方法:
在考虑连接之前,每次使用它们时也应始终关闭ResultSet和Statement对象.不要将它们保存为DataAccess对象中的状态.将它们作为局部变量并在使用后关闭它们:
public String getAge(String name) {
PreparedStatement pst = null;
ResultSet rs = null;
String userage = null;
try {
pst = conn.prepareStatement("select age from mydb where name= ?");
pst.setString(1, name);
rs = pst.executeQuery();
while (rs.next()) {
userage = rs.getString("age");
System.out.println(userage);
}
} catch (Exception ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
} finally {
// closing JDBC resources
if(rs != null) {
rs.close();
}
if(pst != null) {
pst.close();
}
return userage;
}
连接相同:理想情况下,每个方法都应创建一个Connection对象,并在使用后关闭它.根据您在方法中打开和关闭连接的频率,您可能希望使用连接池来共享打开的连接以提高效率.
要关闭连接及其资源,可以创建一个方法来执行此操作:
public void closeConnection(Connection connection, Statement statement, ResultSet resultSet) {
... // close resources here
}
标签:java,database,servlets,dao,jdbc
来源: https://codeday.me/bug/20190623/1274539.html