一、采用JDBC方式访问数据库
1.1、使用JDBC的5个步骤
① 注册驱动和数据库信息
② 获得 Connection,并使用它打开Statement对象
③ 通过 Statement 对象执行SQL语句,并获得结果对象 ResultSet
④ 通过代码将ResultSet 对象转化为 POJO对象
⑤ 关闭数据库资源
1.2、优点
① 只需要会调用JDBC接口中的方法即可。
② 具有代码复用性,只需进行少量修改即可访问其他JDBC支持的数据库。
1.3、缺点
① 代码量大,编码麻烦。
② 需要对异常进行正确捕获并关闭连接。
1.4、Demo
public class UserExecutor {
public static void main(String[] args) throws Throwable {
// 加载驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
// 获得Connection,并使用它打开Statement对象
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/seaking?useSSL=false","root","123456");
// 通过Statement对象执行SQL语句,并获得结果对象ResultSet
ps = connection.prepareStatement("select name,address from role");
rs = ps.executeQuery();
// 通过代码将ResultSet对象转化为POJO对象
while (rs.next()){
System.out.println(String.format("姓名: %s, 上船地点: %s",rs.getString("name"),rs.getString("address")));
}
// 附加: 参数查询带
ps = connection.prepareStatement("select roleId,name,apearNum,address,dgreeId"
+ "from role where roleId = ?");
ps.setInt(1,1);
rs = ps.executeQuery();
while(rs.next()) {
System.out.println(String.format("roleId:%d,姓名:%s,上船集数:%s,上船地点:%s,身份:%d",
rs.getInt("roleId"),rs.getString("name"),rs.getString("apearNum"),
rs.getString("address"),rs.getInt("dgreeId")));
}
} finally {
// 关闭数据库资源
close(connection,ps,rs);
}
}
public static void close(Connection connection,PreparedStatement ps,ResultSet rs) throws Throwable {
if (rs != null && !rs.isClosed()) rs.close();
if (ps != null && !ps.isClosed()) ps.close();
if (connection != null && !connection.isClosed()) connection.close();
System.out.println("资源已关闭");
}
}
二、
— 要养成终生学习的习惯 —
标签:ps,Jdbc,rs,ResultSet,Mybatis,connection,mybatis,close,null From: https://www.cnblogs.com/houhuilinblogs/p/18118499