Jdbc (B station power node old Du) study notes review use

jdbc overview

What is jdbc?

A set of interfaces for connecting to databases in java language, jdbc is a set of interfaces customized by SUN

Why should SUN company develop a set of interfaces?

The underlying implementation principles of each database are different. Programmers need to follow the specifications of which database if they want to use java to connect to a certain database. Imagine that if we programmers want to use another database, we have to follow the specifications of another database, which is very cumbersome.

Therefore, SUN Company develops a set of interfaces, and each database manufacturer is responsible for writing JDBC implementation classes. These implementation classes are stored in jar packages, and these jar packages are drivers. We programmers write code for the JDBC interface.

Quoting a picture of Lao Du at Station B to describe the essence of JDBC:

Use code to explain the essence of JDBC

A set of interfaces developed by SUN

public interface JDBC{
    
    void getConnection();//SUN公司制定的JDBC接口
}


//Mysql数据库公司实现JDBC接口
public class MySql implements JDBC{

    public void getConnection(){
        System.out.println("连接Mysql数据库成功");
    }
}

//程序员面向JDBC接口编程
public class JavaProgrammer{
    public static void main(String[] args){
        JDBC jdbc = new Mysql();//多态
        jdbc.getConnection;
    }
}

Preparatory work before JDBC development

First download the corresponding driver jar package from the official website of the database. The above configuration is for the development of a text editor. When using the IDEA tool, there is no need to configure the above environment variables. IDEA has its own configuration method.

eclipse import jar package

Create a new project, create a new lib file under the project, import the jar package under the lib file, right-click the jar package, click build path, click add to build path, and see the bottle-shaped jar package under Web App Libraries, which means the import is successful

idea import driver

 1. Click File, click Project Structure

 2. Find Libraires and click the + sign to select java

3. Find the jar package path and select it

 

Six steps of JDBC programming:

1. Register the driver (which brand's database to connect to)

2. Get the connection (be sure to close the channel after use)

3. Get the database operation object (the object that specifically executes the sql statement)

4. Execute sql statement

5. Process the query result set (this step is only available if sql is a select statement)

6. Release resources (necessary)        

Code demo:

package com.atdongli.java;
import java.sql.*;
public class JdbcTest {
	public static void main(String[] args) {
			Connection conn = null;
			Statement stmt = null;
			ResultSet rs = null;
			
			try{
				//1.注册驱动
				Class.forName("com.mysql.jdbc.Driver");
				//2.获取连接
				conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db01","root", "2020");
				//3.获取数据库操作对象
				stmt = conn.createStatement();
				//4.执行sql语句
				String sql = "select name,address from users where id = 2 or id = 3";
				//5.处理查询结果集
				// int executeUpdate(insert/delete/update)   //增删改返回处理的数量
				// ResultSet executeQuery(select)	
				rs = stmt.executeQuery(sql);  //专门执行查询语句
				while(rs.next()) {         //jdbc下标从1开始           //如果rs.next()为true  光标会指向结果集的下一行  来完成对结果集的遍历
					String name = rs.getString("name");  //获取结果集的数据用rs.getString()方法:不论数据库中数据是什么类型
					String address = rs.getString("address");//都以String类型形式取出    同理getInt()
					System.out.println(name + "," + address);
				}
			}catch(Exception e) {
				e.printStackTrace();			
			}finally {
				//6.释放资源
				if(rs != null) {
					try {
						rs.close();
					}catch(Exception e){
						e.printStackTrace();
					}
				}
				if(stmt != null) {
					try {
						stmt.close();
					}catch(Exception e) {
						e.printStackTrace();
					}
				}
				if(conn != null) {
					try {
						conn.close();
					}catch(Exception e) {
						e.printStackTrace();
					}
				}
			}
			
		} 
		

		
	}

/*
 * 使用PreparedStatement代替Statement,实现对数据库的增删改查
 * */
public class PrepareStatementTest {
	public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement ps = null;
		
		try{
			//1.注册驱动
			Class.forName("com.mysql.jdbc.Driver");
			//2.获取连接
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db01","root", "2020");
			System.out.println(conn);
			//3.编写sql语句返回preparedStatement的实例
			String sql = "insert into users(name,address) values(?,?)";  //?:表示占位符
			ps =  conn.prepareStatement(sql);
			//4.填充占位符
			ps.setString(1,"诸葛亮");
			ps.setString(2, "三国");
			//5.执行sql语句
			ps.execute();
		}catch(Exception e) {
			e.printStackTrace();			
		}finally {
			//6.释放资源
			if(ps != null) {
				try {
					ps.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			if(conn != null) {
				try {
					conn.close();
				}catch(Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

}

SQL injection problems and solutions

1. What is sql injection?

The information entered by the user contains the keywords of the sql statement, and these keywords participate in the compilation process of the sql statement, causing the intention of the sql statement to be distorted, thereby achieving sql injection.
Statement has sql injection problems, so it leads to PreparedStatement.

2. Solving the problem of sql injection

As long as the information provided by the user does not participate in the compilation process of the sql statement, the problem will be solved. The information provided by the user contains the keywords of the sql statement, but it does not participate in the compilation and does not work. To solve sql injection, java.sql.PreparedStatement must be used. The PreparedStatement interface inherits from Statement and is a precompiled database operation object. The principle is: compile the framework of the sql statement in advance, and then pass the value to the sql statement.

The key is: the information provided by the user contains the keywords of the sql statement, but it does not participate in the compilation and does not work

Comparing Statement and PreparedStatement

Statement has the problem of sql statement injection. PreparedStatement solves this problem.
Statement is compiled once and executed once. PreparedStatement is compiled once and can be executed n times (provided that the sql statement remains unchanged). PreparedStatement is more efficient. PreparedStatement
compiles and performs type safety detection
. To sum up: PreparedStatement is used more, and Statement is used in only a few cases (if you must use sql statement splicing, use Statement)

Guess you like

Origin blog.csdn.net/weixin_53818758/article/details/124566771