这是我们需要进行封装的代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","123456");
//3.获取statement对象
Statement st = conn.createStatement();
//4.查询
ResultSet rs = st.executeQuery("select * from tb");
//5.对结果遍历
while(rs.next()) {
System.out.println(rs.getString(1)+"~~~"+rs.getInt(2)+"~~~"+rs.getInt(3));
}
//6.关闭 rs , st , conn
rs.close();
st.close();
conn.close();
}
}
1.我们先将所需的变量以及对象变成成员变量:
private String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/demo";
private static String password = "123456";
private static String username = "root";
private static Connection conn = null;
private static Statement st = null;
private static ResultSet re = null;
2.将加载驱动定义为静态代码块。
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3.获取连接对象。
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
4.对数据库的添加、删除、修改操作进行封装。
public void update(String sql) {
try {
conn = getConnection();
st = conn.createStatement();
int bRet = st.executeUpdate(sql);
System.out.println(bRet);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
jdbcClose(conn, st);
}
}
5.释放资源。
public static void jdbcClose(Connection conn,Statement st,ResultSet rs) {
try {
rs.close();
if(rs != null) {
rs = null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
st.close();
if(st!=null) {
st = null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
conn.close();
if(conn!=null) {
conn = null;
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
public static void jdbcClose(Connection conn,Statement st) {
try {
st.close();
if(st!=null) {
st = null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
conn.close();
if(conn!=null) {
conn = null;
}
} catch (Exception e) {
// TODO: handle exception
}
}
}