一、Jdbc的执行过程
一个简单的入门Demo:
public static final String URL = "jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=GMT";public static final String USERNAME = "root";public static final String PASSWORD = "root";@Testpublic void streamTest() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); String sql = "select id, order_no, user_name from order_info where id = 1"; Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql); while(rs.next()){
System.out.println("user_name:" + rs.getString(3)); } rs.close(); statement.close(); connection.close();}
二、Jdbc的三种执行器
我们平时最常使用的是PreparedStatment 执行器,因为他能够防止sql注入。在Statement每次执行都是一条条的静态Sql,而PreparedStatement 是一条sql和若干组参数。这样在多次执行的时候,数据的体量较小,所以理论上来性能会更高。当然Statement也有他的优势,就是在一个Statement中,可以执行不同的静态sql。
@Testpublic void preparedStatementTest() throws SQLException {
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); String sql = "select * from order_info where id = ?"; PreparedStatement ps = connection.prepareStatement(sql); ps.setInt(1, 1); ps.execute(); printResultSet(ps); ps.setInt(1, 2); ps.execute(); printResultSet(ps); ps.close();}private void printResultSet(PreparedStatement ps) throws SQLException {
ResultSet rs = ps.getResultSet(); while (rs.next()){
System.out.println(rs.getString(3)); } rs.close();}
三、Mybatis 的执行过程
1、SQL会话SqlSession
org.apache.ibatis.session.SqlSession 接口提供了基本Api,包含了select、s