使用DBUtil类,封装两个静态方法,一个得到连接方法,一个关闭连接方法,以MySQL为例:
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的各种语句执行中还有很多可优化的地方,大家不妨自己多研究一下。
如果文章对你有帮助,欢迎点赞投币,长按点赞可以一键三连!