Educoder/Touge JAVA——Advanced Features of JAVA: JDBD (Part 1)

Table of contents

Level 1: JDBC connection database

related information

Load the database driver

establish connection

Execute the written SQL statement

release resources

programming requirements

Level 2: JDBC operations on data in tables

related information

Specify the database connection

Insert data into the specified table

Query the data in the table

programming requirements

Level 3: JDBC transactions

related information

affairs

Basic Elements of Transactions (ACID)

open transaction

commit and rollback

programming requirements


Level 1: JDBC connection database

related information

JDBC APIThe following interfaces and classes are provided:

DriverManager: List of management database drivers for this class. JDBCThe first driver under which a subprotocol is recognized and used to establish a database connection.

Driver: This interface handles communication with the database server. We rarely Driverinteract directly with objects. To connect to the database in programming, you must first load the database driver of a specific vendor.

Connection: This interface has all the methods for contacting the database. ConnectionThe object represents the communication context, i.e. all communication with the database goes through the connection object only.

Statement: An object used to execute a static SQLstatement and return the result it generates. Some derived interfaces can also accept parameters, eg PrepareStatement.

ResultSet: Provides methods to retrieve fields of different types. (The operation object is the result after Statementexecuting SQLthe query)

SQLException: This class handles any errors that occur in the database application.

The steps used JDBCare as follows:

Load the database driver → establish a database connection ( Connection) → create an object SQLto execute the statement Statement→ process the execution result ( ResultSet) → release resources

In order to complete this task, you need to master: 1. How to load the database driver; 2. How to establish a database connection; 3. How to execute the written SQLstatement; 4. Release resources.

Load the database driver

The driver is loaded to open the communication channel with the database.

Before registering the driver, we need to load the vendor-specific database driver and the imported mysq-connector-javapackage jar. The method is to create a directory in the project liband put the package under it jar.

Then right-click jarthe package Build PathAdd to Build Pathcomplete jarpackage import. After importing jarthe package into the project we start registering the driver:

JavaLoading the database driver usually uses Classthe static method of the class forName(), and the syntax format is as follows:

  1. Class.forName(String driverManager)

Example:

  1. try {
  2. Class.forName("com.mysql.jdbc.Driver" );
  3. } catch (ClassNotFoundException e) {
  4. e.printStackT\frace();
  5. }

If the loading is successful, the loaded driver class will be registered with DriverManager; if the loading fails, ClassNotFoundExceptionan exception will be thrown.

establish connection

After successfully loading the database driver, you can establish a connection to the database, using the DriverManagerstatic method getConnection()to achieve. as follows:

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

URLURLIt is used to identify the location of the database and tell the program connection information through the address JDBC.

If there is no database, only establish a connection, URLwritten as:

If there is a database test, URLthe writing method is:

localhostIt can be replaced with IPan address 127.0.0.1, 3306which is MySQLthe default port number of the database, userand passwordthe user name and password of the corresponding database.

Execute the written SQLstatement

After the connection is established, you can use the method Connectionof the interface createStatement()to obtain Statementthe object; and executeUpdate()execute SQLthe statement through the method.

  • create statementobject

    1. try {
    2. Statement statement = conn.createStatement();
    3. } catch (SQLException e) {
    4. e.printStackT\frace();
    5. }
  • create database

    1. try {
    2. String sql1="drop database if exists test";
    3. String sql2="create database test";
    4. statement.executeUpdate(sql1);//执行sql语句
    5. statement.executeUpdate(sql2);
    6. } catch (SQLException e) {
    7. e.printStackT\frace();
    8. }
  • create table

    1. try {
    2. statement.executeUpdate("use test");//选择在哪个数据库中操作
    3. String sql = "create table table1(" +
    4. "column1 int not null, " +
    5. "column2 varchar(255)" +
    6. ")";
    7. statement.executeUpdate(sql);
    8. } catch (SQLException e) {
    9. e.printStackT\frace();
    10. }

release resources

JdbcAfter the program is running, remember to release the objects that the program created during the running process to interact with the database, these objects are usually ResultSet, Statementand Connectionobjects.

Especially Connectionobjects, which are very rare resources, must be released immediately after use. If they Connectioncannot be closed in a timely and correct manner, it will easily lead to system downtime.

ConnectionThe usage principle is to create as late as possible and release as early as possible.

In order to ensure that the resource release code can run, the resource release code must be placed finallyin the statement.

  1. finally {
  2. try {
  3. if(statement!=null)
  4. statement.close();
  5. if(conn!=null)
  6. conn.close();
  7. } catch (SQLException e) {
  8. e.printStackT\frace();
  9. }
  10. }

programming requirements

Supplement the code in the editor on the right, and complete the following corresponding tasks:

  1. Load the database driver; [The user ( ) of the platform database connection useris root, and the password ( password) is 123123]

  2. Create a database mysql_db;

  3. Create tables student.

studentThe table structure is:

field name type Remark constraint
id int student id non empty
name varchar(20) student name none
sex varchar(4) student gender none
age int student age none
//jdbcConn.java
package jdbc;

import java.sql.*;

public class jdbcConn {
	public static void getConn() {
		try {
			// 1.注册驱动
			Class.forName("com.mysql.jdbc.Driver");

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		/********** End **********/

		/********** Begin **********/
		Connection conn = null;
		Statement statement = null;
		try {
			// 2.建立连接并创建数据库和表
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "123123");
			String sql1 = "drop database if exists mysql_db;";
			String sql2 = "create database mysql_db;";
			statement = conn.createStatement();
			statement.execute(sql1);
			statement.execute(sql2);
			statement.execute("use mysql_db");
			String sql3 = "create table student(id int not null,name varchar(20),sex varchar(4),age int)";
			statement.execute(sql3);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (statement != null)
					statement.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
//test1.java
package jdbcTest;

import jdbc.jdbcConn;
import java.sql.*;

public class Test1 {
    public static void main(String[] args) throws SQLException {
        jdbcConn.getConn();
        try {
            Class.forName("com.mysql.jdbc.Driver" );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String url = "jdbc:mysql://localhost:3306/mysql_db";
        Connection conn = DriverManager.getConnection (url,"root","123123" );
        PreparedStatement pst = null;
        try {
            pst = conn.prepareStatement("select * from student");
            ResultSetMetaData rsd = pst.executeQuery().getMetaData();
            for(int i = 1; i <= rsd.getColumnCount(); i++) {
                String columnTypeName = rsd.getColumnTypeName(i);
                String columnName = rsd.getColumnName(i);
                int columnDisplaySize = rsd.getColumnDisplaySize(i);
                System.out.println(columnName+" "+columnTypeName+"("+columnDisplaySize+")");
            }
        } catch(SQLException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (pst!=null)
                    pst.close();
                if (conn != null)
                    conn.close();
            } catch(SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

Level 2: JDBC operations on data in tables

related information

Specify the database connection

When we already have a database, we can specify the database directly when connecting, as follows to test_dbestablish a connection with the database:

  1. String url = "jdbc:mysql://localhost:3306/test_db";
  2. Connection conn = DriverManager.getConnection (url,"root","123123" );

When the database is specified when connecting, we don't need to write SQLa statement to select the database.

Insert data into the specified table

sqlAfter the connection is established, write a statement to insert data into the table , and use the method Statementof the object executeUpdate()to execute the sqlstatement to modify the data in the table (this method is applicable to statements of insert, update, ). When the statement is a query statement, use the method:deletesqlsqlexecuteQuery()

  1. try {
  2. Statement statement = conn.createStatement();
  3. statement.executeUpdate("insert into table1(column1,column2) values(101,'xxx')");
  4. } catch (SQLException e) {
  5. e.printStackT\frace();
  6. }

PreparedStatement

The above-mentioned direct use Statementinserts data into the table, and there is SQLa risk of injection during the operation, which is separated from the above-mentioned table, as in the following example:

  1. String id = "5";
  2. String sql = "delete from tablename where id=" + id;
  3. Statement st = conn.createStatement();
  4. st.executeQuery(sql);//查询到表中将无数据
  5. //如果用户传入的id为“5 or 1=1”,那么将删除表中的所有记录

SQLIn order to prevent the injection of this situation , PreparedStatementeffectively prevent sqlthe injection ( SQLthe statement has been precompiled before the program runs , and the parameters are passed dynamically when running PreprareStatement, even if there are sensitive characters in the parameters such as or '1=1'database, they will be used as a field attribute of the parameters value to be processed and not as an SQLinstruction)

PreparedStatementUse as follows:

  1. PreparedStatement statement = conn.prepareStatement("insert into table1(column1,column2) values(?,?)");//使用占位符来先占个位置
  2. statement.setInt(1,101);//占位符顺序从1开始,根据数据库中字段相应的类型存入数据
  3. statement.setString(2, "XXX");//也可以使用setObject
  4. statement.executeUpdate();//每执行一个sql语句就需要执行该方法

Query the data in the table

JdbcUsed in a program ResultSetto represent Sqlthe execution result of a statement.

ResultsetWhen encapsulating the execution results, the method is similar to a tableResultSet . The object maintains a cursor pointing to the data row of the table. Initially, the cursor is before the first row. Call ResultSet.next()the method to make the cursor point to the specific data row, and then call the method Get the data for this row.

  1. //编写查询sql语句
  2. PreparedStatement statement = conn.prepareStatement("select * from table1");
  3. ResultSet resultSet = statement.executeQuery();//将执行结果给ResultSet
  4. while (resultSet.next()) {//循环判断表中是否还有数据
  5. int id = resultSet.getInt(1);//通过列的索引查询
  6. String name = resultSet.getString("column2");//通过列名查询
  7. }

programming requirements

mysql_dbSupplement the code in the editor on the right, insert data into the table in the database created in the previous chapter student, and output the inserted data:

id name sex age
1 Zhang San male 19
2 Li Si female 18
3 Wang Wu male 20

Tip: The class has been packaged for you student, you can view it in the folder on the right, and this class can be used directly.

package jdbc;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class jdbcInsert {
    public static void insert(){
		/**********   Begin  **********/
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
		/**********   End   **********/
		Connection conn = null;
		PreparedStatement statement = null;
		/**********   Begin  **********/
        //连接并插入数据
		try{
			String url = "jdbc:mysql://localhost:3306/mysql_db?useUnicode=true&characterEncoding=utf8";
			String user = "root";
			String password = "123123";
			conn = DriverManager.getConnection(url, user, password);

			String sql = "insert into student(id,name,sex,age) values (1,'张三','男',19),(2,'李四','女',18),(3,'王五','男',20)";

			statement = conn.prepareStatement(sql);
			statement.executeUpdate();
			String sql1 = "select * from student";
			ResultSet rs = statement.executeQuery(sql1);

			Student student = null;
			while (rs.next()) {
				int id = rs.getInt(1);
				String name = rs.getString(2);
				String sex = rs.getString(3);
				int age = rs.getInt(4);
				student = new Student(id, name, sex, age);
				System.out.println(
						student.getId() + " " + student.getName() + " " + student.getSex() + " " + student.getAge());
			}
		
		} catch (SQLException e) {
            e.printStackTrace();
        }
		/**********   End   **********/
		finally {
            try {
                if (statement != null)
                    statement.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Level 3: JDBC transactions

related information

affairs

Assuming a scenario, we have a personnel management system. If you want to delete a person, you need to delete not only the basic information of the person, but also the information related to the person, such as mailboxes, articles, etc., so that these database operation statements can be Make a transaction!

Transactions control when changes are committed and applied to the database. It treats a single SQLstatement or group SQLof statements as a logical unit, and if any statement fails, the entire transaction fails.

Basic elements of business ( ACID)

  • Atomicity ( Atomicity): a group of transactions, either succeed; or withdraw;

  • Consistency ( Consistency): Before and after the transaction, the integrity constraints of the database are not violated. For example, when A transfers money to B, it is impossible Ato deduct the money Bbut not receive it;

  • Isolation ( Isolation): Transactions run independently. If the result of a transaction processing affects other transactions, then other transactions will be withdrawn. Transaction 100%isolation requires sacrifice of speed;

  • Persistence ( Durability): After the transaction is completed, all updates made by the transaction to the database will be saved to the database and cannot be rolled back.

open transaction

Opening a thing requires enabling manual transaction support, rather than using JDBCthe autocommit mode that the driver uses by default, on the callable Connectionobject's setAutoCommit()method. If a boolean falseis passed to setAutoCommit(), autocommit is turned off , which is equivalent to turning things on. A boolean can also be passed trueto turn it back on.

  1. Connection conn = DriverManager.getConnection (url,"root","123123" );
  2. conn.setAutoCommit(false);//关闭自动提交开启事务

commit and rollback

In mysqlthe database, the default is to sqlautomatically submit every sentence. When we set it to manual transaction support (that is, the transaction has been manually opened), we can manually submit when we need to submit:

  1. conn.commit();//提交事务

When multiple sqlstatements are submitted at one time, we need to consider sqlwhether they are legal, and if one of them is illegal, sqlwhether the others still need to be changed; to ensure the basic elements of the transaction, we need to manually call the transaction rollback to control sqlThe execution of:

  1. try{
  2. Connection conn = DriverManager.getConnection (url,"root","123123" );
  3. conn.setAutoCommit(false);//开启事务
  4. PreparedStatement ps = conn.prepareStatement("insert into table1(column1,column2) values(1,'xx1')");
  5. ps.executeUpdate();
  6. ps = conn.prepareStatement("insert in table1(column1,column2) values(1,'xx1')");
  7. ps.executeUpdate();
  8. conn.commit();//提交事务
  9. } catch (SQLException e) {
  10. try {
  11. conn.rollback();//回滚事务 回滚到你开始事务之前
  12. } catch (SQLException e1) {
  13. e1.printStackT\frace();
  14. }
  15. }

After the above code is executed, no data will be updated in the database. Because the syntax of the second insertstatement is wrong, the transaction is rolled back and the previous one insertwill be invalidated. Usually transaction rollbacks are placed catchin to capture.

After starting the transaction, be sure to keep up with commitor rollbackrelease the data that may be locked in time.

Not rollback()using it has rollback()the same effect as using it, but not using rollback()it may cause the locked data to not be released in time (you need to wait for things to be released over time), which will affect the next transaction operation.

programming requirements

According to the prompt, supplement the code in the editor on the right, write a new SQLstatement and any wrong statement, and submit the transaction; the first new SQLstatement is required to be modified in the database, and the subsequent wrong SQLstatement is not executed.

The specific requirements for adding an insert statement are as follows: Add a new entry in mysql_dbthe database table for , for Zhao Liu, for female, for data.studentid4namesexage21

Tip:SQL Transactions can be committed after each statement.

package jdbc;

import java.sql.*;

public class jdbcTransaction {

    public static void transaction(){
        try {
            Class.forName("com.mysql.jdbc.Driver" );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Connection conn = null;
        PreparedStatement ps = null;
        /**********  Begin   **********/
        //连接数据库并开启事务
        try {
			String url = "jdbc:mysql://localhost:3306/mysql_db?useUnicode=true&characterEncoding=utf8";
			conn = DriverManager.getConnection(url, "root", "123123");
			conn.setAutoCommit(false);
			String sql = "insert into student(id,name,sex,age) values(4,'赵六','女',21)";
			ps = conn.prepareStatement(sql);
			ps.executeUpdate();
			conn.commit();
			String sql1 = "daj;ljd";
			ps = conn.prepareStatement(sql1);
			ps.executeUpdate();
			conn.commit();
			String sql2 = "select * from student";
			ResultSet rs = ps.executeQuery(sql2);
			Student student = null;
			while (rs.next()) {
				int id = rs.getInt(1);
				String name = rs.getString(2);
				String sex = rs.getString(3);
				int age = rs.getInt(4);
				student = new Student(id, name, sex, age);
				System.out.println(
						student.getId() + " " + student.getName() + " " + student.getSex() + " " + student.getAge());
			}
        } catch (SQLException e) {
            try {
                //回滚
                conn.rollback();
                
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        /**********  End   **********/
        finally {
            try {
                if(ps!=null)
                    ps.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/zhou2622/article/details/128382970