package com.tesjd;
import java.sql.*;
//已测试过
public class DB {
//在使用时都要加载驱动因此放在静态代码块中
static {
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
public static Connection getCon(){
Connection con= null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/work?user=root&password=admin");
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
public static void closeCon(Connection con){
try {
if(con!=null){ java
//有的能够有con = null,但我运行的时候出现了java.lang.NullPointException异常 因此注释了 mysql
//con= null;
con.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
public static Statement getSta(Connection con){
Statement sta= null;
try {
sta=con.createStatement();
}catch(SQLException e){
e.printStackTrace();
}
return sta;
}
public static PreparedStatement getPsta(Connection con,String sql){
PreparedStatement psta= null;
try {
psta= con.prepareStatement(sql);
}catch(SQLException e){
e.printStackTrace();
}
return psta;
}
public static void closeSta(Statement sta){
try {
if(sta!=null){
//sta=null;
sta.close() ;
}
}catch(SQLException e){
e.printStackTrace();
}
}
public static ResultSet executeQuery (Statement sta, String sql)
{
ResultSet res= null;
try {
res= sta.executeQuery(sql); sql
}catch(Exception e){e.printStackTrace();
return res;
}
public static void closeRes(ResultSet res){
try{if(res!=null){
// res=null; //不要乱写 只要这里写了null就会出现nullpoing错误
res.close();
}
}catch(SQLException e){e.printStackTrace();}
} 测试
//重载上面的executeQuery()方法 spa
public static ResultSet executeQuery(Connection con,String sql){ ResultSet res= null; try { res= con.createStatement().executeQuery(sql); }catch(SQLException e){e.printStackTrace();} return res; } }