jdbc连接第一种方法:

//jdbc第一种连接方式(1.0本)-----------------------------------------------------------

//前戏导入mysql-connector包
/*private Connection con;
//得到连接对象的方法
public Connection getCon(){
try {
Class.forName(“com.mysql.jdbc.Driver”);
con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/easybuy”,“root”,“root”);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}

 return  con;

}

//返回增删改结果集的方法(int)
public int methodUtils(String sql,Object[] obj){
int num = 0;
try {
PreparedStatement preparedStatement = getCon().prepareStatement(sql);
if(obj!=null&&obj.length!=0){
for (int i = 0; i <obj.length ; i++) {
preparedStatement.setObject(i+1,obj[i]);
}
}
num = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}

//得到返回查询结果集的方法(ReturnResult)
public ResultSet getAll(String sql, Object[] obj){
ResultSet rs = null;
try {
PreparedStatement preparedStatement = getCon().prepareStatement(sql);
if(obj!=null&&obj.length!=0){
for (int i = 0; i <obj.length ; i++) {
preparedStatement.setObject(i+1,obj[i]);
}
}
rs = preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}

//关闭所有连接对象的方法
public void doClose(ResultSet rs,PreparedStatement ps,Connection con){
//从后关到前
try {
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(con!=null){
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}

猜你喜欢

转载自blog.csdn.net/weixin_42334396/article/details/83305997