Mybatis前篇之JDBC
一、JDBC
java database connection (java操作数据库的标准接口)
以Mysql为例(Innodb存储引擎),操作步骤如下:
1、加载mysql数据库驱动
Class.forName("com.mysql.jdbc.Driver");
2、获取连接对象
Connection conn = DriverManager.getConnection(url,username,password);
3、获取数据库操作对象
PreparedStatement stat = conn.prepareStatement(SQL);
4、SQL
stat.executeQuery()/executeUpdate();
5、返回结果
ResultSet
6、关闭连接对象
conn.close()
二、代码实现(查询数据、插入数据)
package com.imooc.util; import org.junit.jupiter.api.Test; import java.sql.*; public class JDBCUtil { private static String url; private static String driverClassName; private static String username; private static String password; private static Connection connection; private static PreparedStatement ps; private static ResultSet rs; private static String sql; static { url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8"; driverClassName = "com.mysql.jdbc.Driver"; username = "root"; password = "root"; } public static Connection init() { try { //通过反射,JVM加载Driver类,执行Driver类的static静态块(注册驱动) Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(url,"root","root"); } catch ( ClassNotFoundException e ) { System.out.println("驱动类加载失败"); e.printStackTrace(); } catch ( SQLException e ) { System.out.println("创建连接对象失败"); e.printStackTrace(); } return connection; } @Test public void testSel() { connection = JDBCUtil.init(); String sql = "select * from tb_user"; try { ps = connection.prepareStatement(sql); rs = ps.executeQuery(); User user = new User(); while (rs.next()){ user.setId(rs.getInt("id")); user.setName(rs.getString("username")); user.setPassword(rs.getString("password")); System.out.println(user); } } catch ( SQLException e ) { e.printStackTrace(); }finally { try { rs.close(); ps.close(); connection.close(); } catch ( SQLException e ) { e.printStackTrace(); } } } @Test public void testIns(){ try { connection = JDBCUtil.init(); String sql = "insert into tb_user(username,password) values(?,?)"; ps = connection.prepareStatement(sql); User user = new User(); user.setName("erpAdmin"); user.setPassword("erp123!!"); ps.setString(1,user.getName()); ps.setString(2,user.getPassword()); ps.executeUpdate(); System.out.println("插入成功"); } catch ( SQLException e ) { e.printStackTrace(); } } } class User{ private int id; private String name; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + '}'; } }
三、**JDBC的缺点**(引入ORM框架例如:Mybaits的原因)
1、SQL语句和Java代码耦合。
2、需要不断的set/get参数至实体对象。
3、获得连接的代码几乎一样,重复性极高。