[JavaWeb] JDBC detailed introduction


One, JDBC principle

JDBC (Java Database Connectivity): Provides a unified access method for a variety of relational database DBMS, and realizes the use of java to operate the database.


2. Main functions of JDBC API:

DriverManager : Manage JDBC drivers

Connection : Connect to the database (generated by DriverManager)

Statement : Add, delete, modify and check the database. (Generated by Connection)

PreparedStatement : used to execute SQL queries and updates containing dynamic parameters (generated through Connection)

CallableStatement : Call a stored procedure/stored function in the database (generated by Connection)

ResultSet : The returned result set (generated by various statements)


Three, JDBC execution process:

1: Connect to a data source, such as a database.

2: Pass query and update instructions to the database.

3: Process the database response and return the result.


Four, Statement

Statement operation database:
         add, delete and modify: executeUpdate();
         query: executeQuery();
         getString(Int, etc.): get specific value by field name

Code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class JDBCDemo {
    
    
	private static final  String URL = "jdbc:mysql://127.0.0.1:3306/jdbc?serverTimezone=UTC&characterEncoding=UTF-8";
	private static final  String name = "root"; //账号
	private static final  String pwd = "123456"; //密码
	
	public static void update() {
    
     //增删改操作
		
		try{
    
    
			//导入驱动,加载具体的驱动类(新的要加cj)
			Class.forName("com.mysql.cj.jdbc.Driver");
			
			//与数据库建立连接
			Connection conn = DriverManager.getConnection(URL,name,pwd);
			
			//发送sql语句
			Statement stmt = conn.createStatement();
			String sql = "insert into info values('zhangsan',20)";
			
			//执行sql语句
			int count = stmt.executeUpdate(sql); //返回值为修改的行数
			if(count>0){
    
    
				System.out.println("操作成功!");
			}
			
			//关闭连接
			if(stmt!=null) stmt.close();
			if(conn!=null) conn.close();
			
		}catch(Exception e){
    
    
			e.printStackTrace();
		}
	}
	
	public static void query(){
    
     //查询操作
		
		try{
    
    
			//导入驱动,加载具体的驱动类
			Class.forName("com.mysql.cj.jdbc.Driver");
			
			//连接数据库
			Connection conn = DriverManager.getConnection(URL,name,pwd);
			
			//发送sql语句
			Statement stmt = conn.createStatement();
			String sql = "select * from info";
			
			//执行查询,获取结果集
			ResultSet st = stmt.executeQuery(sql);
			
			//处理结果集
			while(st.next()){
    
    
				String name = st.getString("name");
				int age = st.getInt("age");
				System.out.println("姓名:" + name + "    " + "年龄:" + age);
			}
			
			//关闭连接
			if(st!=null) st.close();
			if(stmt!=null) stmt.close();
			if(conn!=null) conn.close();
			
			}catch(Exception e){
    
    
				e.printStackTrace();
			}
	}
	
	public static void main(String[] args) {
    
    
		//update();
		query();
	}
}


五、PreparedStatement

public interface PreparedStatement extends Statement

Sub-interface of Statement

PreparedStatement operation database:
         add, delete and modify: executeUpdate();
         query: executeQuery();
         assignment operation: setString(Int, etc.)

Code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JDBCPreparedStatementDemo {
    
    
	private static final String URL = "jdbc:mysql://127.0.0.1:3306/jdbc?serverTimezone=UTC&characterEncoding=UTF-8";
	private static final String name = "root"; //账号
	private static final String pwd = "123456"; //密码
	
	
	public static void update(){
    
    
		try{
    
    
			//加载驱动
			Class.forName("com.mysql.cj.jdbc.Driver");
			
			//连接数据库
			Connection conn = DriverManager.getConnection(URL,name,pwd);
			
			String sql = "insert into info values(?,?)";
			PreparedStatement pstmt = conn.prepareStatement(sql);  ///预编译
			pstmt.setString(1, "lisi"); //设置第一个?的值
			pstmt.setInt(2, 18); //设置第二个?的值
			
			//cnt表示增删改数据的条数
			int cnt = pstmt.executeUpdate();
			
			if(cnt>0){
    
    
				System.out.println("操作成功!");
			}
			
			//关闭连接
			if(pstmt!=null) pstmt.close();
			if(conn!=null) conn.close();
			
		}catch(Exception e){
    
    
			e.printStackTrace();
		}
	}
	
	public static void query(){
    
    
		try{
    
    
			
			//加载驱动
			Class.forName("com.mysql.cj.jdbc.Driver");
			
			//数据库连接
			Connection conn = DriverManager.getConnection(URL,name,pwd);
			
			String sql = "select * from info";
			PreparedStatement pstmt = conn.prepareStatement(sql);
			
			//查询
			ResultSet st = pstmt.executeQuery();
			
			while(st.next()){
    
    
				String name = st.getString("name");
				int age = st.getInt("age");
				System.out.println("姓名: " + name + "  " + "年龄:" + age);
			} 
			
			//关闭连接
			if(st!=null) st.close();
			if(pstmt!=null) pstmt.close();
			if(conn!=null) conn.close();
		}catch(Exception e){
    
    
			e.printStackTrace();
		}
	}
	
	
	
	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		//update();
		query();
	}

}

operation result:

Insert picture description here


Six, the difference between Statement and PrepareStatement

1 The difference in use:

1.Statement:

(1) String sql = “”

(2) executeUpdate (sql)


2.PreparedStatement:

(1) String sql = "" (There may be placeholders in the sql statement?)

(2) prepareStatement (sql), when the PreparedStatement is created, the sql statement is pre-compiled,

(3) setString(Int, etc.) Replace placeholders?
For example : setString(1,"zhangsan") Replace the position of the first placeholder with "zhangsan"

(4) executeUpdate()



2 Reasons why PreparedStatement is recommended:

1: The coding is simpler and can avoid complicated string splicing

2: Better performance, faster than statement through pre-compilation (execute only once)

3: Using placeholders, the code is highly readable and easy to maintain

4; More secure, effectively prevent SQL injection, and statement has the risk of being injected

(SQL injection: The code entered by the user is mixed with the SQL statement, quotation marks are paired, etc., so that the wrong information is successfully logged in!)


Guess you like

Origin blog.csdn.net/weixin_45260385/article/details/109301754