JDBC连接数据库以及JDBC工具类的创建

本文详细介绍了如何使用Java JDBC进行数据库操作,包括加载MySQL驱动、建立数据库连接、编写SQL语句、创建Statement对象、执行查询与更新操作,并提供了关闭连接的工具方法。通过示例代码展示了完整的数据库查询流程。
摘要由CSDN通过智能技术生成
      1、加载驱动Class.forName("");
      Class.forName("com.mysql.jdbc.Driver");
      2、获得连接对象Connection
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java?useUnicode=true&characterEncoding=UTF-8", "***", "***");
      //前面写上地址,?前面的java是数据库名称,根据实际情况改变,最后两个引号是用户名和密码,根据实际情况改变
       3、写sql语句
      String sql = "SELECT id,name,age,gender FROM student";
      //随便写的
      4、创建Statement(一艘船)
      statement = connection.createStatement();
       5、执行sql语句
      //      (1) 更新类(更改了表里面数据):delete/update/insert     executeUpdate()
      //      返回值:int,表示你影响的行数
      //      (2)查询(没有改变表里面数据):  select                executeQuery()
      //      返回值:结果集ResultSet
      //PreparedStatement 使用预编译的sql
      6、关闭连接
      //先打开后关闭
    if (resultSet != null) {
        try {
            resultSet.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    if (statement != null) {
        try {
            statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    if (connection != null) {
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

JDBC工具类的创建
static {
try {
Class.forName(“com.mysql.jdbc.Driver”);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
加载驱动以静态代码块的方式,避免了每次连接都需要加载一次
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/homework?useUnicode=true&characterEncoding=UTF-8”, “root”, “342516”);
return connection;
}

public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet){
    //先打开后关闭
    if (resultSet != null) {
        try {
            resultSet.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    if (statement != null) {
        try {
            statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    if (connection != null) {
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值