gistfile1.txt public class DBHelper {private Connection conn;private PreparedStatement ps;private ResultSet rs;private static final String DRIVER="com.mysql.jdbc.Driver";private static final String URL="jdbc:mysql://localhost:3306/housedb";
public class DBHelper {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
private static final String DRIVER="com.mysql.jdbc.Driver";
private static final String URL="jdbc:mysql://localhost:3306/housedb";
private static final String USER="root";
private static final String PWD="root";
//加载驱动
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//打开连接
private void openConnection()throws ClassNotFoundException,SQLException {
if(conn==null || conn.isClosed()) {
conn=DriverManager.getConnection(URL, USER, PWD);
}
}
//关闭连接
public void close()throws SQLException{
if(rs!=null) rs.close();
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
//增删改辅助方法
public int executeUpdate(String sql,Object...obj)throws ClassNotFoundException,SQLException {
openConnection();
ps=conn.prepareStatement(sql);
setParams(obj);
return ps.executeUpdate();
}
//为占位符赋值
private void setParams(Object...obj)throws ClassNotFoundException,SQLException {
if(obj!=null && obj.length>0) {
for (int i = 0; i < obj.length; i++) {
ps.setObject(i+1, obj[i]);
}
}
}
//查询的辅助方法
public ResultSet executeQuery(String sql,Object...obj)throws ClassNotFoundException,SQLException {
openConnection();
ps=conn.prepareStatement(sql);
setParams(obj);
return ps.executeQuery();
}
}
