JDBC第一篇【JDBC入门】

什么时JDBC?

答:JDBC全称时Java Data Base Connectivity,是执行sql语句的Java Api。

使用JDBC的步骤:

  1. 导入数据库驱动包
  2. 注册驱动
  3. 获取数据库连接
  4. 获取执行Sql语句的对象
  5. 执行Sql
  6. 关闭连接
    public void JDBC() {
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取数据库连接
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC", "root", "12345678");
            //获取执行Sql语句的对象
            Statement statement = connection.createStatement();
            //执行Sql
            ResultSet resultSet = statement.executeQuery("select  * from user ");
            //遍历结果集
            while (resultSet.next()) {
                System.out.println(resultSet.getString(1));
                System.out.println(resultSet.getString(2));
                System.out.println(resultSet.getString(3));
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            /*
            关闭资源时,先使用的后关闭
            关闭前判断是否为null
            */
            try {
                if (resultSet != null)
                    resultSet.close();
                if (statement != null)
                    statement.close();
                if (connection != null)
                    connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

猜你喜欢

转载自www.cnblogs.com/kwdlh/p/12660671.html