使用DBUtil类,封装两个静态方法,一个得到连接方法,一个关闭连接方法
import java.sql.*;
public class DBUtil {
//创建连接
public static Connection get_conn(){
String url = "jdbc:mysql://localhost/JDBC?useSSL=false";
String user = "zhaomingxuan";
String password = "123456";
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);
}
}