[JDBC] JDBC basic implementation

Detailed JDBC

JDBC concept:

​ JDBC (Java Data Base Connectivity, java database connection) is a Java API used to execute SQL statements, which can provide unified access to a variety of relational databases. It consists of a set of classes and interfaces written in Java language. JDBC provides a benchmark from which more advanced tools and interfaces can be built to enable database developers to write database applications.

Common interfaces:

1.Driver interface

The Driver interface is provided by the database manufacturer. As a java developer, you only need to use the Driver interface. To connect to the database in programming, you must first load the specific manufacturer's database driver. Different databases have different loading methods. Such as:

Load MySql driver:

Class.forName("com.mysql.jdbc.Driver");

Load the Oracle driver:

Class.forName("oracle.jdbc.driver.OracleDriver");

2.Connection interface

Connection with a specific database connection (session), execute sql statement in the connection context and return the result. The DriverManager.getConnection(url, user, password) method is established on the database Connection connection defined in the JDBC URL.

Connect to MySql database:

Connection conn = DriverManager.getConnection("jdbc:mysql://host:port/database", "user", "password");

Connect to the Oracle database:

Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@host:port:database", "user", "password");

Connect to the SqlServer database:

Connection conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://host:port; DatabaseName=database", "user", "password");

Common methods:

    • createStatement(): Create a statement object that sends sql to the database.
    • prepareStatement(sql): Create a PrepareSatement object that sends precompiled sql to the database.
    • prepareCall(sql): Create a callableStatement object that executes a stored procedure.
    • setAutoCommit(boolean autoCommit): Set whether the transaction is automatically committed.
    • commit(): Commit the transaction on the link.
    • rollback(): Roll back the transaction on this link.

3.Statement interface

The object used to execute static SQL statements and return the results it generates.

Three Statement classes:

    • Statement: Created by createStatement, used to send simple SQL statements (without parameters).
    • PreparedStatement: inherited from the Statement interface, created by preparedStatement, and used to send SQL statements containing one or more parameters. PreparedStatement objects are more efficient than Statement objects and can prevent SQL injection, so we generally use PreparedStatement.
    • CallableStatement: Inherited from the PreparedStatement interface, created by the method prepareCall, used to call a stored procedure.

Common Statement methods:

    • execute(String sql): run the statement and return whether there is a result set
    • executeQuery(String sql): Run the select statement and return the ResultSet result set.
    • executeUpdate(String sql): Run insert/update/delete operations and return the number of updated rows.
    • addBatch(String sql): Put multiple sql statements into one batch.
    • executeBatch(): Send a batch of SQL statements to the database for execution.

4. ResultSet interface

ResultSet provides methods to retrieve different types of fields, the commonly used ones are:

    • getString(int index), getString(String columnName): Obtain data objects of varchar, char and other types in the database.
    • getFloat(int index), getFloat(String columnName): Get the data object of type Float in the database.
    • getDate(int index), getDate(String columnName): Get data of type Date in the database.
    • getBoolean(int index), getBoolean(String columnName): Obtain Boolean data in the database.
    • getObject(int index), getObject(String columnName): Get any type of data in the database.

ResultSet also provides a method to scroll the result set:

    • next(): move to the next line
    • Previous(): Move to the previous line
    • absolute(int row): move to the specified row
    • beforeFirst(): Move the top of the resultSet.
    • afterLast(): Move to the end of resultSet.

Close the object and connection after use: ResultSet → Statement → Connection

Steps to use JDBC:

Load the JDBC driver → establish a database connection → create a statement that executes SQL Statement → process the execution result ResultSet → release resources

1. Register the driver (do it only once)

Method 1 : Class.forName("com.MySQL.jdbc.Driver");
  This method is recommended and will not depend on specific driver classes.
  Method 2 : DriverManager.registerDriver(com.mysql.jdbc.Driver);
  will cause two identical drivers in DriverManager, and will depend on specific driver classes.

2. Establish a connection

 Connection conn = DriverManager.getConnection(url, user, password); 

URL is used to identify the location of the database, and tell the JDBC program which database to connect to through the URL address. The URL is written as:
Insert picture description here
  other parameters such as: useUnicode=true&characterEncoding=utf8

3. Create a statement that executes SQL statements

1 //Statement  
2 String id = "5";
3 String sql = "delete from table where id=" +  id;
4 Statement st = conn.createStatement();  
5 st.executeQuery(sql);  
6 //存在sql注入的危险
7 //如果用户传入的id为“5 or 1=1”,那么将删除表中的所有记录
1  //PreparedStatement 有效的防止sql注入(SQL语句在程序运行前已经进行了预编译,当运行时动态地把参数传给PreprareStatement时,即使参数里有敏感字符如 or '1=1'也数据库会作为一个参数一个字段的属性值来处理而不会作为一个SQL指令)
2 String sql = “insert into user (name,pwd) values(?,?);  
3 PreparedStatement ps = conn.preparedStatement(sql);  
4 ps.setString(1, “col_value”);  //占位符顺序从1开始
5 ps.setString(2,123456); //也可以使用setObject
6 ps.executeQuery(); 

4. Processing execution results (ResultSet)

1 ResultSet rs = ps.executeQuery();  
2 While(rs.next()){
    
      
3     rs.getString(“col_name”);  
4     rs.getInt(1);  
5     //…
6 }  

5. Release resources

 //数据库连接(Connection)非常耗资源,尽量晚创建,尽量早的释放 //都要加try catch 以防前面关闭出错,后面的就不执行了 1 try {
    
    
 2     if (rs != null) {
    
    
 3         rs.close();
 4     }
 5 } catch (SQLException e) {
    
    
 6     e.printStackTrace();
 7 } finally {
    
    
 8     try {
    
    
 9         if (st != null) {
    
    
10             st.close();
11         }
12     } catch (SQLException e) {
    
    
13         e.printStackTrace();
14     } finally {
    
    
15         try {
    
    
16             if (conn != null) {
    
    
17                 conn.close();
18             }
19         } catch (SQLException e) {
    
    
20             e.printStackTrace();
21         }
22     }
23 } 

Affairs

The transaction must meet four conditions (ACID) :: atomic ( A tomicity, also known as indivisibility), consistency ( C onsistency), isolation ( the I solation, also known as independence), persistence ( D urability) .

  • ** Atomicity: ** All operations in a transaction are either completed or not completed at all, and will not end in a certain link in the middle. If an error occurs during the execution of the transaction, it will be rolled back (Rollback) to the state before the transaction started, as if the transaction had never been executed.
  • **Consistency:** The integrity of the database is not destroyed before the transaction begins and after the transaction ends. This means that the written data must fully comply with all preset rules, which includes the accuracy and continuity of the data, and the subsequent database can spontaneously complete the scheduled work.
  • **Isolation: **The ability of the database to allow multiple concurrent transactions to read, write and modify its data at the same time. Isolation can prevent data inconsistencies caused by cross execution when multiple transactions are executed concurrently. Transaction isolation is divided into different levels, including read uncommitted (read uncommitted), read committed (read committed), repeatable read (repeatable read) and serialization (Serializable).
  • **Persistence:** After the transaction is completed, the modification of the data is permanent, and it will not be lost even if the system fails.

Isolation level

JDBC instance

Insert picture description here

package com.myobject.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.myobject.dao.FlowerDao;
import com.myobject.pojo.Flower;

public class FlowerDaoImpl implements FlowerDao{
    
    
	
	
	
	@Override
	public List<Flower> selAll() {
    
    
		List<Flower> list= new ArrayList<Flower>();
		Connection conn= null;
		PreparedStatement ps= null;
		ResultSet rs= null;
	
		try {
    
    
			Class.forName("com.mysql.jdbc.Driver");
			conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/usermanage", "root", "121891");
			ps= conn.prepareStatement("select * from flower");
			rs= ps.executeQuery();
			while(rs.next()) {
    
    
				list.add(new Flower(rs.getInt("id"), rs.getString("name"), rs.getDouble("price"), rs.getString("production")));
			}
			
		} catch (ClassNotFoundException e) {
    
    
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (SQLException e) {
    
    
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}finally {
    
    
			try {
    
    
				rs.close();
			} catch (SQLException e) {
    
    
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			try {
    
    
				ps.close();
			} catch (SQLException e) {
    
    
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			try {
    
    
				conn.close();
			} catch (SQLException e) {
    
    
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}	
		return list;
	}
	
	@Override
	public int insFlower(Flower flower) {
    
    
		Connection conn= null;
		PreparedStatement ps= null;
		int index= 0;
		try {
    
    
			Class.forName("com.mysql.jdbc.Driver");
			conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/usermanage", "root", "121891");
			ps= conn.prepareStatement("insert into flower values (default,? ,? , ?)");
			
			ps.setObject(1, flower.getName());
			ps.setObject(2, flower.getPrice());
			ps.setObject(3, flower.getProduction());
			index= ps.executeUpdate();
			
		} catch (ClassNotFoundException e) {
    
    
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (SQLException e) {
    
    
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}finally {
    
    
			
			try {
    
    
				ps.close();
			} catch (SQLException e) {
    
    
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			try {
    
    
				conn.close();
			} catch (SQLException e) {
    
    
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}	
		return index;
	}
}

Similarities and differences between Statement and PreparedStatement and their advantages and disadvantages

Same: Both are used to execute SQL statements

Difference: PreparedStatement needs to be created based on SQL statements. It can specify corresponding values ​​by setting parameters, instead of using string splicing like Statement.

Advantages of PreparedStatement:

1. It uses parameter settings, which is easy to read and not easy to remember. The use of string concatenation in the statement is relatively poor in readability and maintainability.

2. It has a pre-compilation mechanism, and its performance is faster than statement.

3. It can effectively prevent SQL injection attacks.

The difference between execute and executeUpdate

Similarities: Both can perform operations such as adding, deleting, and modifying.

difference:

1. Execute can execute the query statement, and then retrieve the result through getResult. executeUpdate cannot execute the query statement.

2. Execute returns Boolean type, true means the query statement is executed, false means insert, delete, update, etc. are executed. The return value of executeUpdate is int, which indicates how many pieces of data were affected.




Disclaimer: This blog post is a study note and refers to network resources. If there is any infringement, please inform us by private message!

Guess you like

Origin blog.csdn.net/qq_42380734/article/details/105491480