使用DBUtil类,封装两个静态方法,一个获得链接方法,一个关闭链接方法,以MySQL为例:java
import java.sql.*;
public class DBUtil {
//建立链接
public static Connection get_conn(){
String url = "jdbc:mysql://localhost/JDBC?useSSL=false";
String user = "root";
String password = "root";
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//关闭链接
public static void close_conn(Connection conn, Statement st, PreparedStatement pst){
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pst != null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
使用JDBC_test进行测试数据库操做:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBC_test {
public static void main(String[] args) {
Connection conn = DBUtil.get_conn();
PreparedStatement pst = null;
ResultSet re = null;
try {
String sql = "insert into person values('李志', '25', '南京')";
pst = conn.prepareStatement(sql);
pst.execute();
String sql1 = "select * from person";
pst = conn.prepareStatement(sql1);
pst.execute();
re = pst.executeQuery(sql1);
while (re.next()){
System.out.print("name:" + re.getString(1) + " age:" +re.getString(2) + " address:" + re.getString(3) +"\n");
}
} catch (SQLException e) {
e.printStackTrace();
}
DBUtil.close_conn(conn, null, pst);
}
}
复制代码
针对数据库链接操做封装成类,须要数据库操做直接经过类名来调用,在JDBC的各类语句执行中还有不少可优化的地方,你们不妨本身多研究一下。mysql