jdbc原生代码
1、示例代码
// 注册驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
// 建立链接
Connection connection =
DriverManager.getConnection(
"jdbc:mysql://xxxxx?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&createDatabaseIfNotExist=true&&zeroDateTimeBehavior=convertToNull",
"xx",
"xx");
// 编写sql进行预编译
String sql =
"select a.context_id,a.context_type_id from context_account_info a where a.context_id=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "e49513422c3f40b28ae7a7f67bedc658");
// 执行查询得到结果集
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String context_id = resultSet.getString("context_id");
Integer context_type_id = resultSet.getInt("context_type_id");
String result =
String.format("contextId:%s contextTypeId:%d", context_id, context_type_id);
System.out.println(result);
}
// 关闭事务,关闭的顺序与创建的顺序相反
resultSet.close();
preparedStatement.close();
connection.close();
2、额外说明
- 注册驱动有两种方式
- DriverManager.registerDriver(new com.mysql.jdbc.Driver());
- Class.forName("com.mysql.jdbc.Driver");
- driver分mysql8.0前后版本
- 8.0版本以下的数据库的驱动名 com.mysql.jdbc.Driver
- 8.0版本以上的数据库的驱动名 com.mysql.cj.jdbc.Driver
正文到此结束