当前位置:网站首页>[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.DriverTwo 、 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);
}边栏推荐
- Uniapp uses canvas to generate posters and save them locally
- Rotating frame target detection mmrotate v0.3.1 learning model
- Verilog state machine
- JS <2>
- Global and Chinese markets for hand hygiene monitoring systems 2022-2028: Research Report on technology, participants, trends, market size and share
- Qualcomm platform wifi-- WPA_ supplicant issue
- Discussion on related configuration of thread pool
- Go execute shell command
- verilog REG 寄存器、向量、整数、实数、时间寄存器
- Verilog avoid latch
猜你喜欢

Golang configure export goprivate to pull private library code

GB/T-2423. XX environmental test documents, including the latest documents

小米青年工程师,本来只是去打个酱油

命名块 verilog

Docker installs canal and MySQL for simple testing and implementation of redis and MySQL cache consistency

JIT deep analysis

Screenshot literacy tool download and use

Tupu software has passed CMMI5 certification| High authority and high-level certification in the international software field

2022-2028 global soft capsule manufacturing machine industry research and trend analysis report

SAML2.0 notes (I)
随机推荐
Xiaomi, a young engineer, was just going to make soy sauce
Verilog 线型wire 种类
Global and Chinese market of handheld ultrasonic scanners 2022-2028: Research Report on technology, participants, trends, market size and share
Find duplicates [Abstract binary / fast and slow pointer / binary enumeration]
MMSegmentation系列之训练与推理自己的数据集(三)
venn图取交集
Just a few simple steps - start playing wechat applet
Global and Chinese market of autotransfusion bags 2022-2028: Research Report on technology, participants, trends, market size and share
GB/T-2423.xx 环境试验文件,整理包括了最新的文件里面
Global and Chinese markets for ultrasonic probe disinfection systems 2022-2028: Research Report on technology, participants, trends, market size and share
4. Find the median of two positive arrays
焱融看 | 混合云时代下,如何制定多云策略
Aaaaaaaaaaaa
创业了...
JS introduction < 1 >
竞争与冒险 毛刺
2022-2028 global encryption software industry research and trend analysis report
C#联合halcon脱离halcon环境以及各种报错解决经历
Global and Chinese markets for infant care equipment, 2022-2028: Research Report on technology, participants, trends, market size and share
GB/T-2423. XX environmental test documents, including the latest documents