Table of contents
Level 1: JDBC connection database
Execute the written SQL statement
Level 2: JDBC operations on data in tables
Specify the database connection
Insert data into the specified table
Basic Elements of Transactions (ACID)
Level 1: JDBC connection database
related information
JDBC API
The following interfaces and classes are provided:
DriverManager
: List of management database drivers for this class. JDBC
The 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 Driver
interact 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. Connection
The 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 SQL
statement 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 Statement
executing SQL
the query)
SQLException
: This class handles any errors that occur in the database application.
The steps used JDBC
are as follows:
Load the database driver → establish a database connection ( Connection
) → create an object SQL
to 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 SQL
statement; 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-java
package jar
. The method is to create a directory in the project lib
and put the package under it jar
.
Then right-click jar
the package Build Path
→ Add to Build Path
complete jar
package import. After importing jar
the package into the project we start registering the driver:
Java
Loading the database driver usually uses Class
the static method of the class forName()
, and the syntax format is as follows:
Class.forName(String driverManager)
Example:
try {
Class.forName("com.mysql.jdbc.Driver" );
} catch (ClassNotFoundException e) {
e.printStackT\frace();
}
If the loading is successful, the loaded driver class will be registered with DriverManager
; if the loading fails, ClassNotFoundException
an exception will be thrown.
establish connection
After successfully loading the database driver, you can establish a connection to the database, using the DriverManager
static method getConnection()
to achieve. as follows:
Connection conn = DriverManager.getConnection(url, user, password);
URL
URL
It 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, URL
written as:
If there is a database test
, URL
the writing method is:
localhost
It can be replaced with IP
an address 127.0.0.1
, 3306
which is MySQL
the default port number of the database, user
and password
the user name and password of the corresponding database.
Execute the written SQL
statement
After the connection is established, you can use the method Connection
of the interface createStatement()
to obtain Statement
the object; and executeUpdate()
execute SQL
the statement through the method.
-
create
statement
objecttry {
Statement statement = conn.createStatement();
} catch (SQLException e) {
e.printStackT\frace();
}
-
create database
try {
String sql1="drop database if exists test";
String sql2="create database test";
statement.executeUpdate(sql1);//执行sql语句
statement.executeUpdate(sql2);
} catch (SQLException e) {
e.printStackT\frace();
}
-
create table
try {
statement.executeUpdate("use test");//选择在哪个数据库中操作
String sql = "create table table1(" +
"column1 int not null, " +
"column2 varchar(255)" +
")";
statement.executeUpdate(sql);
} catch (SQLException e) {
e.printStackT\frace();
}
release resources
Jdbc
After 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
, Statement
and Connection
objects.
Especially Connection
objects, which are very rare resources, must be released immediately after use. If they Connection
cannot be closed in a timely and correct manner, it will easily lead to system downtime.
Connection
The 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 finally
in the statement.
finally {
try {
if(statement!=null)
statement.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackT\frace();
}
}
programming requirements
Supplement the code in the editor on the right, and complete the following corresponding tasks:
-
Load the database driver; [The user ( ) of the platform database connection
user
isroot
, and the password (password
) is123123
] -
Create a database
mysql_db
; -
Create tables
student
.
student
The 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_db
establish a connection with the database:
String url = "jdbc:mysql://localhost:3306/test_db";
Connection conn = DriverManager.getConnection (url,"root","123123" );
When the database is specified when connecting, we don't need to write SQL
a statement to select the database.
Insert data into the specified table
sql
After the connection is established, write a statement to insert data into the table , and use the method Statement
of the object executeUpdate()
to execute the sql
statement 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:delete
sql
sql
executeQuery()
try {
Statement statement = conn.createStatement();
statement.executeUpdate("insert into table1(column1,column2) values(101,'xxx')");
} catch (SQLException e) {
e.printStackT\frace();
}
PreparedStatement
The above-mentioned direct use Statement
inserts data into the table, and there is SQL
a risk of injection during the operation, which is separated from the above-mentioned table, as in the following example:
String id = "5";
String sql = "delete from tablename where id=" + id;
Statement st = conn.createStatement();
st.executeQuery(sql);//查询到表中将无数据
//如果用户传入的id为“5 or 1=1”,那么将删除表中的所有记录
SQL
In order to prevent the injection of this situation , PreparedStatement
effectively prevent sql
the injection ( SQL
the 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 SQL
instruction)
PreparedStatement
Use as follows:
PreparedStatement statement = conn.prepareStatement("insert into table1(column1,column2) values(?,?)");//使用占位符来先占个位置
statement.setInt(1,101);//占位符顺序从1开始,根据数据库中字段相应的类型存入数据
statement.setString(2, "XXX");//也可以使用setObject
statement.executeUpdate();//每执行一个sql语句就需要执行该方法
Query the data in the table
Jdbc
Used in a program ResultSet
to represent Sql
the execution result of a statement.
Resultset
When 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.
//编写查询sql语句
PreparedStatement statement = conn.prepareStatement("select * from table1");
ResultSet resultSet = statement.executeQuery();//将执行结果给ResultSet
while (resultSet.next()) {//循环判断表中是否还有数据
int id = resultSet.getInt(1);//通过列的索引查询
String name = resultSet.getString("column2");//通过列名查询
}
programming requirements
mysql_db
Supplement 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 SQL
statement or group SQL
of 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 impossibleA
to deduct the moneyB
but not receive it; -
Isolation (
Isolation
): Transactions run independently. If the result of a transaction processing affects other transactions, then other transactions will be withdrawn. Transaction100%
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 JDBC
the autocommit mode that the driver uses by default, on the callable Connection
object's setAutoCommit()
method. If a boolean false
is passed to setAutoCommit()
, autocommit is turned off , which is equivalent to turning things on. A boolean can also be passed true
to turn it back on.
Connection conn = DriverManager.getConnection (url,"root","123123" );
conn.setAutoCommit(false);//关闭自动提交开启事务
commit and rollback
In mysql
the database, the default is to sql
automatically 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:
conn.commit();//提交事务
When multiple sql
statements are submitted at one time, we need to consider sql
whether they are legal, and if one of them is illegal, sql
whether 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 sql
The execution of:
try{
Connection conn = DriverManager.getConnection (url,"root","123123" );
conn.setAutoCommit(false);//开启事务
PreparedStatement ps = conn.prepareStatement("insert into table1(column1,column2) values(1,'xx1')");
ps.executeUpdate();
ps = conn.prepareStatement("insert in table1(column1,column2) values(1,'xx1')");
ps.executeUpdate();
conn.commit();//提交事务
} catch (SQLException e) {
try {
conn.rollback();//回滚事务 回滚到你开始事务之前
} catch (SQLException e1) {
e1.printStackT\frace();
}
}
After the above code is executed, no data will be updated in the database. Because the syntax of the second insert
statement is wrong, the transaction is rolled back and the previous one insert
will be invalidated. Usually transaction rollbacks are placed catch
in to capture.
After starting the transaction, be sure to keep up with commit
or rollback
release 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 SQL
statement and any wrong statement, and submit the transaction; the first new SQL
statement is required to be modified in the database, and the subsequent wrong SQL
statement is not executed.
The specific requirements for adding an insert statement are as follows: Add a new entry in mysql_db
the database table for , for Zhao Liu, for female, for data.student
id
4
name
sex
age
21
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();
}
}
}
}