当前位置:网站首页>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();
}
}
}
}
边栏推荐
- Image 24 bit depth to 8 bit depth
- The second largest gay dating website in the world was exposed, and the status of programmers in 2022
- Self executing function
- Sepconv (separable revolution) code recurrence
- How to draw non overlapping bubble chart in MATLAB
- 042. (2.11) do it when it's time to do it
- The vscode code is automatically modified to a compliance code when it is formatted and saved
- Use of unsafe class
- CTO and programmer were both sentenced for losing control of the crawler
- Solve the problem of inaccurate network traffic monitored by ZABBIX with SNMP
猜你喜欢

2022-2028 global plasmid DNA cdmo industry research and trend analysis report

Computer graduation design PHP sports goods online sales system website

Xception for deeplab v3+ (including super detailed code comments and original drawing of the paper)

2022-2028 global sepsis treatment drug industry research and trend analysis report

Why can deeplab v3+ be a God? (the explanation of the paper includes super detailed notes + Chinese English comparison + pictures)

English grammar_ Noun classification

Mysql45 lecture learning notes (II)
![[enumeration] annoying frogs always step on my rice fields: (who is the most hateful? (POJ hundred practice 2812)](/img/50/f89092b492d0138304209a72ff05b4.jpg)
[enumeration] annoying frogs always step on my rice fields: (who is the most hateful? (POJ hundred practice 2812)

Multifunctional web file manager filestash
![[Yu Yue education] theoretical mechanics reference materials of Shanghai Jiaotong University](/img/52/b97c618a8f2eb29ad0ccca221bb5c1.jpg)
[Yu Yue education] theoretical mechanics reference materials of Shanghai Jiaotong University
随机推荐
Usage of laravel conditional array in
2022-2028 global plasmid DNA cdmo industry research and trend analysis report
Redis core technology and practice - learning notes (VIII) sentinel cluster: sentinel hung up
Golang string (string) and byte array ([]byte) are converted to each other
[combinatorics] generating function (example of generating function | calculating generating function with given general term formula | calculating general term formula with given generating function)
2022-2028 global physiotherapy clinic industry research and trend analysis report
NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线
多媒体NFT聚合平台OKALEIDO即将上线,全新的NFT时代或将来临
[combinatorics] generating function (example of using generating function to solve the number of solutions of indefinite equation)
041. (2.10) talk about manpower outsourcing
[combinatorics] generating function (positive integer splitting | repeated ordered splitting | non repeated ordered splitting | proof of the number of repeated ordered splitting schemes)
A. Odd Selection【BruteForce】
Codeforces Round #803 (Div. 2) C. 3SUM Closure
How do microservices aggregate API documents? This wave of operation is too good
[combinatorics] generating function (commutative property | derivative property | integral property)
[Godot] add menu button
199. Right view of binary tree - breadth search
The second largest gay dating website in the world was exposed, and the status of programmers in 2022
Class exercises
The number of incremental paths in the grid graph [dfs reverse path + memory dfs]