sql-原生jdbc连接7步

原生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();
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();
}
}
上一篇:jupyter notebook常用快捷键


下一篇:lsmod语法