java JDBC数据库简单使用,封装连接,关闭

使用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);

    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值