Article Directory
JDBC summary
A, JDBC Introduction
- JDBC (Java Data Base Connectivity) API is a set of application programming interfaces for the Java language to access the database.
- Essentially, that is the agreement between the caller (programmer) and implementers (database vendors).
- jDBC implementation provided by the database vendor in the form of drivers.
- JDBC API allows developers to use pure java way to link database, and operate it.
Two, JDBC principle
Three, JDBC object introduction
Jdbc common class
The JDBC core classes have: DriverManager, Connnection, Statement and ResultSet
1, the role of the DriverManager (drive manager) has two
-
Registration drive: This lets JDBC know which drive you want to use
DriverManager.registerDriver()方法:
You can understand, the registration drive for general useClass.forName()
-
Gets Connection: If you can get to the Connection, then that is already connected to the database on
getConnection()方法:
2, Connection object represents a connection and communication with the database is through the expansion of the object:
- Connection is the most important method used to obtain a Statement object
Statement statement = connection.createStatement();
Code:
3, Statement is used to send SQL statements to the database, so the database will be sent by the implementation of SQL statement:
Commonly used methods Statement
int executeUpdate(String sql):执行更新操作(insert,update,delete等)
- Perform update operations that insert, update, delete statement
- You can also perform create table, alter table, drop table and other statements, but rarely used
- Returns the number of rows is operating
ResultSet executeQuery(String sql):执行查询操作,数据库在执行查询后会把查询结果ResultSet返回
- Execute the query operation, namely the select statement
- Back ResultSet, i.e. the result sets
boolean execute();
- Can be used to perform all the sql statement executeUpdate and executeQuery two methods can be performed, i.e., you can perform all the sql statement CRUD
- This method returns a boolean indicating whether the SQL statement has a result set
- If the update statement with this method, you have to call int
getUpdateCount () to get the number of rows affected insert, update, delete statement - If you use this method to execute a query statement, but also calls ResultSet getResult () to get the select statement query results
Three kinds of Statement objects
Statement 对象
- Role: to perform simple SQL statement with no parameters
- Features: each SQL statement is executed, the database must execute compiled SQL statement, the best situation is performed only once for a query and returns the results,
- More efficient than PreparedStatement
PreparedStatement
- Role: to perform with or without IN parameters of pre-compiled SQL statement
- Features:
- ① is precompiled, in the implementation of variable parameters of a SQL statement, more efficient than Statement, as a pre-compiled SQL DBMS, of course, many times more than a compiled SQL higher efficiency
- ② safety, prevent SQL injection and other issues
- ③ For a statement executed repeatedly, it is more efficient, and in this case also more suitable for use batch
- ④ code readability and maintainability good
CallableStatement
- Role: A call to a database stored procedure for execution
- Features: it provides support for input and output parameters
- This interface supports having input and output parameters of the interfaces provided PreparedStatment
Code:
4, ResultSet object represents a query result set only perform the operation will be after generating a query result set
- The result set is a two-dimensional form, there are row has columns.
- To set the operation result using the "cursor row" inside ResultSet, and acquiring data on each column of the current row
boolean next();是行光标移动到下一行,并返回移动后的行是否存在
getXXX(int index);获取指针所指向的当前行数据
colose();释放资源
Four, JDBC programming steps
Need to introduce mysql-connector-java-5.1.39-bin.jar kit.
1, mysql database-driven load
/**
* 所有的java.sql.Driver实现类,都提供了static块,
* 块内的代码就是把自己注册到DriverManager中
*/
Class.forName("com.mysql.jdbc.Driver"); //加载驱动类(注册驱动)
/*等价于*/
com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver(); //注册驱动
DriverManager.registerDriver(driver);
Usually with the Class.forName () method of driving load.
2, Get Link
//设置参数
String url = "jdbc:mysql://localhost:3306/mybase";
String username = "root";
String password = "123";
//使用url,username,password,得到连接对象
Connection connection = DriverManager.getConnection(url,username,password);
3, get Statement
(1) Statement object to obtain
Statement stm = conn.createStatement();
(2) to obtain the object preparedStatement
String sql = "select * from emp where job=?";
pstm = conn.prepareStatement(sql); //创建sql半成品
pstm.setString(1,"clerk"); //参数绑定
The value part of the SQL statement changes with placeholders obtaining PreparedStatement object through the connection, create: ① create sql semi-finished products? instead.
② parameter binding, that is? Assignment (set[type](1,2)方法
) The first parameter represents the position from the beginning;? The second argument is a specific value.
4, execute SQL statements
(1) If the Statement object query, use ResultSet rs = stm.executeQuery(sql);
(2) If the object is preparedStatement query, use ResultSet rs = pstm.executeQuery();
(3) If there are a lot of sql statement needs to be performed, it is necessary to use批处理。
5, the result set (query needs)
while(rs.next()){
String number = rs.getString(1); //通过列编号来获取该列的值
String name = rs.getString("name"); //通过列名称来获取该列的值
int age = rs.getInt(3);
String gender = rs.getString(4);
System.out.println(number + "," + name + "," + age + "," + gender);
}
6, the close link
// 倒关(先得到的资源后关闭,后得到的资源先关闭)
rs.close();
stm.close();
conn.close(); //这个必须要关
V. specification code sample
1, create a connection to the database Statement
import java.sql.*;
public class testStatement {
public static void main(String[] args) {
Connection conn = null;
Statement stm = null;
ResultSet rs = null;
try {
//1、加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取连接
String url = "jdbc:mysql://localhost:3306/mybase?serverTimezone=UTC";
String user = "root";
String password = "159357";
conn = DriverManager.getConnection(url, user, password);
//3、创建Statement对象
stm = conn.createStatement();
//4、执行sql语句
//查询数据库statement.executeQuery(查询sql)
String sql = "select * from emp";
rs = stm.executeQuery(sql);
//修改操作数据库 statement.executeUpdate(增删改sql)
/*String sql = "insert into emp(ename,job,deptno) values('小龙人','manager',10)";
String sql = "delete from emp where ename='小龙人'";
String sql = "update emp set job='leader' where ename='张伟'";
int lines = stm.executeUpdate(sql);
System.out.println("影响的行数"+lines);
*/
//5、处理结果集
while(rs.next()){
//int empno = rs.getInt(1);
int empno = rs.getInt("empno");
String ename = rs.getString(2);
String job = rs.getString(3);
int mgr = rs.getInt(4);
Date hiredate = rs.getDate(5);
double sal= rs.getDouble(6);
//double comm = rs.getDouble(7);
double comm = rs.getDouble("comm");
int deptno = rs.getInt(8);
System.out.println(empno+" "+ename+" "+job+" "+mgr
+" "+hiredate+" "+sal+" "+comm+" "+deptno);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
//6.关闭链接
if(resultSet != null)
{
resultSet.close();
}
if(statement != null)
{
statement.close();
}
if(connection != null)
{
connection.close();
}
}
}
3. Create a database connection preparedStatement
pstm build dynamic sql
resolve Sql injection vulnerabilities, can be performed using sql PreparedStatement. It is
a sub-step of using the interface Statemnet three steps:
(1) Create: PreparedStatement object obtained through links
String sql="select * from user_luxw where username=? Andpassowrd=?";
PreoparedStatment pstm = conn.prepareStatement(sql);
创建时,将SQL语句中取值发生变化的部分用占位符(?)替代。
(2) to? Assignment (also called parameter binding)
/*使用set[Type]方法给?赋值。其中Type表示?表示?位置的数据类型。第一个参数代表问号
位置从1开始;第二个参数是具体取值,比如:*/
pstm.setString(1,username);
pstm.setString(2,password);
(3) the implementation of SQL
pstm.executeQuery();
pstm.executeUpdate(); //执行更新时使用
此时JDBC将所有?对应的参数发送至数据库服务器,调用在共享池中由第一步创建的预编译的SQL并执行
Complete code:
package jdbc;
import java.sql.*;
import java.util.Date;
/**
- 类说明:
- JDBC创建PreparedStatement对象连接数据库
*/
public class testPreparedStatement {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
// 1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获取连接
String url = "jdbc:mysql://localhost:3306/mybase?useUnicode=true&characterEncoding=utf-8";
String user = "root";
String password = "123";
conn = DriverManager.getConnection(url, user, password);
// 3.创建PreparedStatement,预编译sql语句
String sql = "select * from emp where job=?";
pstm = conn.prepareStatement(sql);//创建sql半成品
pstm.setString(1,"clerk");//参数绑定
//4.执行sql语句
rs = pstm.executeQuery();
//5.处理结果集
while(rs.next()){
int empno = rs.getInt("empno");
String ename = rs.getString("ename");
String job = rs.getString(3);
int mgr = rs.getInt("mgr");
Date hiredate = rs.getDate(5);
double sal = rs.getDouble("sal");
double comm = rs.getDouble("commit");
int deptno = rs.getInt(8);
System.out.println(empno+" "+ename+" "+job+" "+mgr+" "+hiredate+" "+sal+" "+comm+" "+deptno);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 6.关闭连接/释放资源
try {
rs.close();
pstm.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
4, Statement and compare preparedStatement
- Execution statement: Create stm Object -> compile -> execute (execute a sql statement 10 seconds).
- Execution of PreparedStatement:
Create Object pstm (sql semi) -> set value -> performing data transmission (sql statement performs a 12 seconds, and the values set sql but requires only 2 seconds)
5, Batch
(1) Statement completed batch
- Add a batch using the Statement object to execute SQL statements
- Executing batch SQL statement:
Statement.executeBatch();
- Clear batch commands:
Statement.clearbatch();
Advantages: you can send a number of different SQL statements to the database.
Drawback: SQL statement is not pre-compiled.
When sending multiple statements to the same database, but only parameters different SQL statements, to be repeated on many write SQL statements.
Complete code:
import java.sql.*;
/*
* statement批处理
*/
public class testStatementBatch {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//加载链接
Class.forName("com.mysql.jdbc.Driver");
//获取链接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybase?serverTimezone=UTC", "root", "159357");
//创建Statement
Statement stm = conn.createStatement();
String sql = "insert into emp(ename,job,deptno) values('小龙人','clerk',20)";
String sql1 = "insert into emp(ename,job,deptno) values('美人鱼','leader',10)";
String sql2 = "update emp set ename='小龙人1' where ename='小龙人'";
//添加批处理
stm.addBatch(sql);
stm.addBatch(sql1);
stm.addBatch(sql2);
//执行批处理ִ
stm.executeBatch();
//清除批处理
stm.clearBatch();
//释放资源
stm.close();
conn.close();
}
}
(2) PreoparedStatment batch
- Using
PrepareStatement.addBatch()
batch processing
Advantages: transmission is that the pre-compiled SQL statements, high efficiency
disadvantages: SQL statement can only be applied in the same, but different batch parameters, thus often used for this form of batch bulk insert a table in the same data, or data batch updates the table.
import java.sql.*;
/*
* prepareStatement批处理
*/
public class testPreparedStatemnetBatch {
public static void main(String[] args) throws Exception {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//获取链接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybase?serverTimezone=UTC", "root", "159357");
String sql="insert into emp(empno,ename,deptno) values(?,?,?)";
//创建preparedStatemet
PreparedStatement pstm = conn.prepareStatement(sql);
//pstm绑定数据
for(int i=3008;i<4008;i++){
pstm.setInt(1, i);
pstm.setString(2, "李白"+i);
pstm.setInt(3,20);
//添加批处理
pstm.addBatch();
//ִ执行批处理
if(i%100==0){
pstm.executeBatch();
pstm.clearBatch();
}
}
//执行批处理
pstm.executeBatch();
//释放资源
pstm.close();
conn.close();
}
}