原生jdbc链接一般分为7步, 来获取链接并执行sql语句

1, 准备4大参数

    static {
        url = "jdbc:mysql://localhost:3306/test" ;
        driveClassName = "com.mysql.jdbc.Driver";
        userName = "root" ;
        password = "root" ;
    }

2, 注册驱动

# 使用Class注册
 Class.forName(driveClassName);

# 使用DriverManager注册
DriverManager.registDriver( new com.mysql.jdbc.Driver() );

3, 获取链接

connect = DriverManager.getConnection(url, userName, password);

4, 执行sql语句

       String sql = "select * from sys_user";
            state = connect.prepareStatement(sql);

5, 获取结果集

 resultSet = state.executeQuery();

6, 结果集处理

      while (resultSet.next()) {
                String name = resultSet.getString("name");
                String sex = resultSet.getString(2);
                System.out.println(name + ": " + sex);
            }

7, 关闭连接

 if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (state != null) {
                try {
                    state.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connect != null) {
                try {
                    connect.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

 

相关文章:

  • 2022-12-23
  • 2021-10-19
  • 2022-12-23
  • 2021-08-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-09
猜你喜欢
  • 2022-01-01
  • 2021-05-11
  • 2021-11-30
  • 2021-04-16
  • 2021-12-30
  • 2021-11-26
  • 2021-07-27
相关资源
相似解决方案