阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

MyBatis在谈JDBC

99次阅读
没有评论

共计 1357 个字符,预计需要花费 4 分钟才能阅读完成。

1、回顾 JDBC

public static void main(String[] args) {Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try {// 加载数据库驱动 Class.forName("com.mysql.jdbc.Driver"); // 通过驱动管理类获取数据库链接 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8","root", "root"); // 定义 sql 语句 ? 表示占位符 String sql = "select * from user where username = ?"; // 获取预处理 statement preparedStatement = connection.prepareStatement(sql); // 设置参数,第一个参数为 sql 语句中参数的序号 (从 1 开始),第二个参数为设置的参数值 preparedStatement.setString(1, "王五"); // 向数据库发出 sql 执行查询,查询出结果集 resultSet = preparedStatement.executeQuery(); // 遍历查询结果集 while(resultSet.next()){System.out.println(resultSet.getString("id")+""+resultSet.getString("username")); } } catch (Exception e) {e.printStackTrace(); }finally{// 释放资源 if(resultSet!=null){try {resultSet.close(); } catch (SQLException e) {e.printStackTrace(); } } if(preparedStatement!=null){try {preparedStatement.close(); } catch (SQLException e) {e.printStackTrace(); } } if(connection!=null){try {connection.close(); } catch (SQLException e) {// TODO Auto-generated catch block e.printStackTrace(); } } } } /* 加载驱动 获取连接 connection 获取预处理对象 statement 设置 sql(采用占位符,防止 sql 注入) 给占位符设置值 执行获取结果集 对结果集进行封装 释放资源 */

2、JDBC 遇到的问题

资源浪费:不断的对连接的创建和释放。(连接池可以解决)

代码不易维护:SQL 发生变化代码就要发生变化。(

SQL 语句发生变化;

如:select * from user; / select * from project;

SQL 条件发生变化;

如:select * from user where id=?; / select * from user username=?

查询结果发生变化;

如:select * from user where age>?

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-06-06发表,共计1357字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中