300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > mysql jdbc关闭连接_【B站Java两分钟】JDBC数据库简单使用 封装连接 关闭

mysql jdbc关闭连接_【B站Java两分钟】JDBC数据库简单使用 封装连接 关闭

时间:2022-09-09 14:48:42

相关推荐

mysql jdbc关闭连接_【B站Java两分钟】JDBC数据库简单使用 封装连接 关闭

使用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的各种语句执行中还有很多可优化的地方,大家不妨自己多研究一下。

如果文章对你有帮助,欢迎点赞投币,长按点赞可以一键三连!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。