当前位置:网站首页>Getting started with JDBC
Getting started with JDBC
2022-07-03 18:35:00 【Bieyunchao】
One 、 What is? JDBC?
Concept :Java DataBase Connectivity Java Database connection , Java Language operation database
Two 、JDBC The essence
JDBC The essence : Actually, it's official (sun company ) A set of rules defined to operate all relational databases , Interface . Each database manufacturer to implement this set of interface , Provide database driver jar package . We can use this interface (JDBC) Programming , The code that actually executes is the driver jar The implementation class in the package .
3、 ... and 、JDBC Quick start
1.JDBC Six steps to programming
First step : Registration drive ( effect : tell Java Program , Which brand database will be connected soon )
The second step : Get database connection ( Express JVM The channel between the database process and the database process is opened , This belongs to communication between processes , A heavyweight , Be sure to close the channel after use .)
The third step : Get database operation object ( Special execution sql Object of statement )
Step four : perform SQL sentence (DQL DML....)
Step five : Process query result set ( Only if the fourth step is select At the time of statement , The fifth step is to process the query result set .)
Step six : Release resources ( Be sure to close the resource after using it .Java And database belong to the communication between processes , Be sure to turn it off after you turn it on .)
2.JDBC Quick start
package com.aynu.jdbc;
import cn.aynu.pojo.User;
import java.sql.*;
/** * Inquire about tab_user surface */
public class JDBCTest04 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet resultSet = null;
try {
// 1. Registration drive
Class.forName("com.mysql.jdbc.Driver");
// 2. Get the connection
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db",
"root",
"root");
// 3. Get database operation object
stmt = conn.createStatement();
// 4. perform sql sentence
String sql = "select * from tab_user";
resultSet = stmt.executeQuery(sql);
// 5. Process query result set
User u = new User();
while (resultSet.next()){
String id = resultSet.getString("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
Date birthday = resultSet.getDate("birthday");
u.setId(id);
u.setName(name);
u.setAge(age);
u.setBirthday(birthday);
System.out.println(u);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
// 6. Release resources
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
Four 、 Detailed explanation JDBC Each object
1.DriverManager
DriverManager: Drive management objects
function :
1. Registration drive : Tell the driver of the corresponding database used by the program
Code :Class.forName("com.mysql.jdbc.Driver");
Source code analysis : stay com.mysql.jdbc.Driver Class has static code blocks
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
Be careful :mysql5 After the drive jar Packages can omit the steps of registering drivers .
2. Get database connection
Method :static Connection getConnection(String url, String user, String password)
Parameters :
url: Specify the path of the connection
grammar :jdbc:mysql://ip Address ( domain name ): Port number / Database name
Example :jdbc:mysql://localhost:3306/db
user: user name (mysql The user name of the database )
root: password (mysql Database password )
2.Connection
Connection: Database connection object
Access method :conn = DriverManager.getConnection(url, user, password);
function :
1. Access to perform sql Object of statement
conn.createStatement()
conn.prepareStatement(sql);
2. Manage affairs
Open transaction :conn.setAutoCommit(false);
Commit transaction :conn.commit();
Transaction rollback :conn.rollback();
Be careful : Here conn Generation refers to Connection object
3.Statement
Statement: perform sql The object of
Access method :Statement stmt = conn.createStatement();
1. perform sql
1. boolean execute(String sql) :
You can do whatever you want sql
2. int executeUpdate(String sql) :
It can be executed DML(insert、update、delete) sentence 、
DDL(create,alter、drop) sentence
* Return value : Number of rows affected , It can be judged by the number of rows affected DML Is the statement executed successfully
* Return value >0 Then the execution is successful , conversely , The failure .
3. ResultSet executeQuery(String sql) :
perform DQL(select) sentence
4.ResultSet
ResultSet: Result set object , Encapsulate query results
Access method :ResultSet resultSet = stmt.executeQuery(sql);
boolean next(): Move the cursor down one line , Determine whether the current line is the end of the last line ( Is there any data ),
If it is , Then return to false, If not, return true
* getXxx( Parameters ): get data
* Xxx: Representative data type Such as : int getInt() , String getString()
* Parameters :
1. int: Represents the number of the column , from 1 Start Such as : getString(1)
2. String: Name of representative column . Such as : getDouble("balance")
while (resultSet.next()){
// Get the data of this row in the database
String id = resultSet.getString("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
Date birthday = resultSet.getDate("birthday");
}
5. PreparedStatement
PreparedStatement: perform sql The object of ( Precompiled objects )
Access method :PrepareStatement pstmt = conn.prepareStatement(sql);
1. SQL Injection problem : In splicing sql when , Somewhat sql Special keywords participate in string splicing .
Can cause security problems
2 solve sql Injection problem : Use PreparedStatement Object to solve
2. precompiled SQL: Parameters use ? As placeholder
package com.aynu.jdbc;
import java.sql.*;
import java.util.Scanner;
/** * Practice using PreparedStatement * Implement login function id name */
public class JDBCTest05 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
try {
// 1. Registration drive
Class.forName("com.mysql.jdbc.Driver");
// 2. Get the connection
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/day04",
"root", "root");
// 3. Get database operation object
// Definition sql sentence
String sql = "select * from tab_user where id = ? and name = ?";
pstmt = conn.prepareStatement(sql);
System.out.print("id:");
String id = new Scanner(System.in).nextLine();
System.out.print("name:");
String name = new Scanner(System.in).nextLine();
// to ? assignment
pstmt.setString(1, id);
pstmt.setString(2, name);
// 4. perform sql sentence
resultSet = pstmt.executeQuery();
// 5. Process query result set
if (resultSet.next()){
System.out.println(" Landing successful ");
} else{
System.out.println(" Login failed ");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 6. Release resources
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
5、 ... and 、 Extract tool class
It is obvious from the above two code cases ,JDBC Code is not complicated , however Duplicate code A lot , So we need to extract a tool class , The following is a tool class I extracted in this stage of study , And configuration files ( take driver,url,user,password Extract a properties in ), You can also use it .
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=utf-8
user=root
password=root
Be careful : In daily study
?useUnicode=true&characterEncoding=utf-8user=root
To deal with the problem of Chinese garbled code
package com.aynu.util;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
/** * JDBC Tool class */
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
/** * Static code block , Used to load configuration files */
static {
try {
Properties pro = new Properties();
String path = Thread.currentThread().getContextClassLoader().getResource("jdbc.properties").getPath();
pro.load(new FileInputStream(path));
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
// Registration drive
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/** * Get the connection * @return Connection object */
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
/** * Release resources * @param stmt * @param conn */
public static void close(Statement stmt, Connection conn){
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/** * Release resources * @param rs * @param stmt * @param conn */
public static void close(ResultSet rs,Statement stmt, Connection conn){
if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
边栏推荐
- Sensor 调试流程
- After the festival, a large number of people change careers. Is it still time to be 30? Listen to the experience of the past people
- [combinatorics] dislocation problem (recursive formula | general term formula | derivation process)*
- Torch learning notes (6) -- logistic regression model (self training)
- Mysql45 lecture learning notes (II)
- [tutorial] build your first application on coreos
- Sepconv (separable revolution) code recurrence
- 2022-2028 global copper foil (thickness 12 μ M) industry research and trend analysis report
- [Yu Yue education] world reference materials of Microbiology in Shanghai Jiaotong University
- Class exercises
猜你喜欢

Gao Qing, Beijing University of Aeronautics and Astronautics: CIM is a natural quantum computing platform for graph data processing

Read the paper glodyne global topology preserving dynamic network embedding

win32:堆破壞的dump文件分析

Administrative division code acquisition

How do microservices aggregate API documents? This wave of operation is too good

NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
![[combinatorics] dislocation problem (recursive formula | general term formula | derivation process)*](/img/e8/67961bf8a589869bde2a0aa3e09605.jpg)
[combinatorics] dislocation problem (recursive formula | general term formula | derivation process)*

Summary and Reflection on the third week of winter vacation

2022-2028 global petroleum pipe joint industry research and trend analysis report
![AcWing 271. Teacher Yang's photographic arrangement [multidimensional DP]](/img/3d/6d61fefc62063596221f98999a863b.png)
AcWing 271. Teacher Yang's photographic arrangement [multidimensional DP]
随机推荐
How to quickly view the inheritance methods of existing models in torchvision?
2022-2028 global sepsis treatment drug industry research and trend analysis report
Count the number of pixel values in the image
[combinatorics] generating function (use generating function to solve the combination number of multiple sets R)
[combinatorics] exponential generating function (properties of exponential generating function | exponential generating function solving multiple set arrangement)
Gao Qing, Beijing University of Aeronautics and Astronautics: CIM is a natural quantum computing platform for graph data processing
PHP MySQL where clause
论文阅读 GloDyNE Global Topology Preserving Dynamic Network Embedding
Use of unsafe class
[combinatorics] generating function (property summary | important generating function)*
A. Odd Selection【BruteForce】
ES7 - Optimization of promise
[combinatorics] generating function (commutative property | derivative property | integral property)
[combinatorics] generating function (positive integer splitting | unordered | ordered | allowed repetition | not allowed repetition | unordered not repeated splitting | unordered repeated splitting)
win32:堆破壞的dump文件分析
2022-2028 global physiotherapy clinic industry research and trend analysis report
[combinatorics] generating function (positive integer splitting | unordered non repeated splitting example)
What does foo mean in programming?
2022-2028 global marking ink industry research and trend analysis report
How does GCN use large convolution instead of small convolution? (the explanation of the paper includes super detailed notes + Chinese English comparison + pictures)