当前位置:网站首页>[database]jdbc
[database]jdbc
2022-07-02 03:20:00 【Sing the wind tonight】
What is? JDBC?
JDBC(Java Database Connectivity) It's a ** Independent of a specific database management system 、 General purpose SQL A common interface for database access and operation **( A group of API), Defines the criteria for accessing databases Java Class library ,(**java.sql,javax.sql**) These libraries can be used in a ** standard ** Methods 、 Easy access to database resources .
How to use JDBC?
It is roughly divided into six steps , Namely :
① The load driver
② Link to the database
③ Create a through connection SQL Command transmitter Statement( Better avoidance SQL Injected is now used prepareStatement)
④ Use SQL The command sender sends... To the database SQL command .
⑤ Processing results
⑥ close resource
Next, we will elaborate and expand according to these six steps
One 、 The load driver
The original and mechanical writing is as follows :
@Test
public void testConnection1() {
try {
//1. Provide java.sql.Driver The interface implements the object of the class
Driver driver = null;
driver = new com.mysql.jdbc.Driver();
//2. Provide url, Data indicating the specific operation
String url = "jdbc:mysql://localhost:3306/test";
//3. Provide Properties The object of , Indicate the user name and password
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "abc123");
//4. call driver Of connect(), Get the connection
Connection conn = driver.connect(url, info);
System.out.println(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
But now, it is generally used to declare the basic information required by the database in the configuration file and obtain the connection by reading the configuration file .
First, manually create Properties file
Under the contents of the document ;
# Configuration information
user=root
password= Your password
url=jdbc:mysql://localhost:3306/ Database name ?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true
driverClass=com.mysql.jdbc.Driver
Two 、 Connect to database
Then load the contents of the file to complete the connection drive :
/**
* Use the Druid database connection driver
*/
private static DataSource ds;
static {
try {
Properties pro = new Properties();
pro.load(TestDruid.class.getClassLoader().getResourceAsStream("druid.properties"));
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConn1() throws SQLException {
Connection conn = ds.getConnection();
return conn;
}
// Get database connection
notes : Encapsulating the statement that creates an object into a static code block is a resource-saving approach , If it is written in the method, it will create many times and waste resources .
3、 ... and 、 Create a through connection SQL Command transmitter Statement( Better avoidance SQL Injected is now used prepareStatement)
Take the general addition, deletion, modification and query methods as an example :
/**
* General addition, deletion and modification
* @param sql
* @param args
* @throws SQLException
* @throws ClassNotFoundException
*/
public static void update(String sql, Object... args) {
Connection conn = null;
PreparedStatement pre = null;
try {
conn = JDBCUtils.getConn();
pre = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
pre.setObject(i + 1, args[i]);
}
pre.execute();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.closeResource(conn, pre);
}
}
pre.excute; Indicates execution , But the execution statement of query is different from that of addition, deletion and modification :
/**
* Inquire about
* @param sql
* @param args
* @throws SQLException
* @throws ClassNotFoundException
*/
public static List<SelectTools> select1(String sql, Object... args) {
Connection conn = null;
PreparedStatement pre = null;
ResultSet resultSet=null;
try {
conn = JDBCUtils.getConn1();
pre = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++){
pre.setObject(i +1,args[i]);
}// When there are variable parameters ,args Equivalent to an array ,
// The underlying system will first determine its length and then create an array of the same length , Then get the parameters and traverse the array .
resultSet =pre.executeQuery();
int columnCount=rsmd.getColumnCount();
List<SelectTools> list = new ArrayList<>();
while (resultSet.next()){
SelectTools se=new SelectTools();
for (int i = 0; i <columnCount; i++) {
Object columnValue= resultSet.getObject(i+1);
String columnName=rsmd.getColumnLabel(i+1);
Field file= SelectTools.class.getDeclaredField(columnName);
file.setAccessible(true);
file.set(se,columnValue);
}
list.add(se);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource1(conn,pre,resultSet);
}
return null;
}
Execution block is different from adding, deleting and modifying : Encapsulated as a result set
resultSet =pre.executeQuery();
Processing result set
if(resultSet.next()){
// Determine whether the next item in the result set has data , If there is, go back true, And the pointer moves down , Reverse return false, The pointer does not move down .
// Get the value of each field
int id=resultSet.getInt(1);
String name=resultSet.getString(2);
.......... And so on
}
Four 、 Use SQL The command sender sends... To the database SQL command .
Generally will SQL Written in the execution class ( Test class ):
Prepare in advance : Write a tool class that declares field attributes in advance , The attribute is consistent with the field or alias used for adding, deleting, and modifying the query .
public class SelectTools {
private String name;
private String com;
private int count;
@Override
public String toString() {
return "SelectTools{" +
"name='" + name + '\'' +
", com='" + com + '\'' +
", count=" + count +
'}';
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCom() {
return com;
}
public void setCom(String com) {
this.com = com;
}
public SelectTools() {
}
}
Then in the execution class ( Test class ) It defines and writes SQL sentence :
public class QueryRunnerTest {
@Test
public void QueryRunnerTest() throws SQLException {
Connection conn= null;
try {
conn = JDBCUtils.getConn1();
QueryRunner runner=new QueryRunner();
String sql="SELECT p.p_name `name`,COUNT(*) `count`\n" +
"FROM sales s,deal d,production p\n" +
"WHERE s.s_no=d.s_no AND p.p_no=d.p_no\n" +
"GROUP BY d.p_no";
MapListHandler handler=new MapListHandler();
List<Map<String,Object>> wan = runner.query(conn,sql,handler);
wan.forEach(System.out::println);}
}
}
Because there is no operation to close resources , The implementation is not very fast .
The above query is driven by the Druid database connection and uses Druid Of jar The encapsulated query method in the package .
5、 ... and 、 Processing results
ResultSet The role of classes
ResultSet( Result set ) Is the data table of the database result set , Typically generated by executing statements that query the database
One ResultSet Object corresponds to a table returned by the query statement, which contains all the query results . It can be said that the result set is an object to store query results , But the result set doesn't just have the function of storage , He also has the ability to manipulate data , May complete the data update, etc .
actually , We can put one ResultSet Object as a table . Yes ResultSet Objects must be processed line by line , And for each column in each row , Can be processed in any order .
Be careful :Java Interaction with the database is related to Java API All the indexes in are from 1 Start .
// Processing result set
try {
conn = JDBCUtils.getConn1();
pre = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++){
pre.setObject(i +1,args[i]);
}// When there are variable parameters ,args Equivalent to an array ,
// The underlying system will first determine its length and then create an array of the same length , Then get the parameters and traverse the array .
resultSet =pre.executeQuery();
int columnCount=rsmd.getColumnCount();
List<SelectTools> list = new ArrayList<>();
while (resultSet.next()){
SelectTools se=new SelectTools();
for (int i = 0; i <columnCount; i++) {
Object columnValue= resultSet.getObject(i+1);
String columnName=rsmd.getColumnLabel(i+1);
Field file= SelectTools.class.getDeclaredField(columnName);
file.setAccessible(true);
file.set(se,columnValue);
}
list.add(se);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource1(conn,pre,resultSet);
}
return null;
6、 ... and 、 close resource
Closing resources is basically a if Judge not empty , Then close the resource according to the judgment result .
/** For query
* close resource ( Contains the result set )
* @param conn
* @param pre
*/
public static void closeResource1(Connection conn, PreparedStatement pre, ResultSet resultSet){
// The simplest way to write it is to call DbUtils The method inside , Its bottom layer is consistent with the normal writing :
DbUtils.closeQuietly(conn);
DbUtils.closeQuietly(pre);
DbUtils.closeQuietly(resultSet);
// Normal writing :
// try{
// if (pre != null) {
// pre.close();
// }
// } catch (SQLException e) {
// e.printStackTrace();
// }
// try {
// if (pre != null) {
// conn.close();
// }
// } catch (SQLException e) {
// e.printStackTrace();
// }
// try {
// if (resultSet != null) {
// conn.close();
// }
// } catch (SQLException e) {
// e.printStackTrace();
// }
}
in the light of Blob Operation of type field :
type | byte |
TinyBlob | 255B |
Blob | 65Kb |
LongBLOb | 4G |
MediumBlob | 16M |
notes : If you specify Blob The type will report an error later , look for my.ini File plus
max_allowed_packed=16M And then restart mysql service .
// Insert big data types into the data table
// Get the connection
Connection conn = JDBCUtils.getConnection();
String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
// Fill in placeholders
ps.setString(1, " Xu Haiqiang ");
ps.setString(2, "[email protected]");
ps.setDate(3, new Date(new java.util.Date().getTime()));
// operation Blob Variable of type
FileInputStream fis = new FileInputStream("xhq.png");
ps.setBlob(4, fis);
// perform
ps.execute();
fis.close();
JDBCUtils.closeResource(conn, ps);
// Read big data types from the data table
//……
String sql = "SELECT id, name, email, birth, photo FROM customer WHERE id = ?";
conn = getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, 8);
rs = ps.executeQuery();
if(rs.next()){
Integer id = rs.getInt(1);
String name = rs.getString(2);
String email = rs.getString(3);
Date birth = rs.getDate(4);
Customer cust = new Customer(id, name, email, birth);
System.out.println(cust);
// Read Blob Type field
Blob photo = rs.getBlob(5);
InputStream is = photo.getBinaryStream();
OutputStream os = new FileOutputStream("c.jpg");
byte [] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer)) != -1){
os.write(buffer, 0, len);
}
JDBCUtils.closeResource(conn, ps, rs);
if(is != null){
is.close();
}
if(os != null){
os.close();
}
}
The batch operation , According to the characteristics of transactions, you can operate in batches :
give an example : Insert... Into the data table 20000 Data
/*
*
* Use Connection Of setAutoCommit(false) / commit()
*/
@Test
public void testInsert2() throws Exception{
long start = System.currentTimeMillis();
Connection conn = JDBCUtils.getConnection();
//1. Set to not automatically submit data
conn.setAutoCommit(false);
String sql = "insert into goods(name)values(?)";
PreparedStatement ps = conn.prepareStatement(sql);
for(int i = 1;i <= 1000000;i++){
ps.setString(1, "name_" + i);
//1.“ Save ”sql
ps.addBatch();
if(i % 500 == 0){
//2. perform
ps.executeBatch();
//3. Empty
ps.clearBatch();
}
}
//2. Submit data
conn.commit();
long end = System.currentTimeMillis();
System.out.println(" The time spent is :" + (end - start));//1000000 strip :4978
JDBCUtils.closeResource(conn, ps);
}
边栏推荐
- Rotating frame target detection mmrotate v0.3.1 learning model
- Use blocking or non blocking for streamline
- Large screen visualization from bronze to the advanced king, you only need a "component reuse"!
- Xiaomi, a young engineer, was just going to make soy sauce
- How to create an instance of the control defined in SAP ui5 XML view at runtime?
- JIT deep analysis
- Apple added the first iPad with lightning interface to the list of retro products
- A list of job levels and salaries in common Internet companies. Those who have conditions must enter big factories. The salary is really high
- PMP personal sprint preparation experience
- 2022 hoisting machinery command examination paper and summary of hoisting machinery command examination
猜你喜欢
Form custom verification rules
[JS reverse series] analysis of a customs publicity platform
West digital decided to raise the price of flash memory products immediately after the factory was polluted by materials
Baohong industry | what misunderstandings should we pay attention to when diversifying investment
C shallow copy and deep copy
Start a business
Named block Verilog
命名块 verilog
[golang] leetcode intermediate bracket generation & Full Permutation
Force deduction daily question 540 A single element in an ordered array
随机推荐
汇率的查询接口
Verilog 状态机
Gradle notes
halcon图像矫正
C reflection practice
JS introduction < 1 >
Verilog wire type
Principle of computer composition - interview questions for postgraduate entrance examination (review outline, key points and reference)
[HCIA continuous update] overview of dynamic routing protocol
Redis set command line operation (intersection, union and difference, random reading, etc.)
Aaaaaaaaaaaa
浅谈线程池相关配置
Download and use of the super perfect screenshot tool snipaste
Mathematical calculation in real mode addressing
SAML2.0 notes (I)
PMP personal sprint preparation experience
MMSegmentation系列之训练与推理自己的数据集(三)
el-table的render-header用法
Rotating frame target detection mmrotate v0.3.1 learning model
旋转框目标检测mmrotate v0.3.1 学习模型