当前位置:网站首页>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();
}
}
}
}
边栏推荐
- 编程中常见的 Foo 是什么意思?
- 2022-2028 global solid phase extraction column industry research and trend analysis report
- What London Silver Trading software supports multiple languages
- Ping problem between virtual machine and development board
- Sensor 调试流程
- This diversion
- SDNUOJ1015
- 12、 Service management
- FBI 警告:有人利用 AI 换脸冒充他人身份进行远程面试
- The number of incremental paths in the grid graph [dfs reverse path + memory dfs]
猜你喜欢

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

Win32: analyse du fichier dump pour la défaillance du tas

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

English grammar_ Noun classification

Grammaire anglaise Nom - Classification

Redis core technology and practice - learning notes (VIII) sentinel cluster: sentinel hung up

Data analysis is popular on the Internet, and the full version of "Introduction to data science" is free to download

Torch learning notes (3) -- univariate linear regression model (self training)

Implementation of cqrs architecture mode under Kratos microservice framework

Sensor 调试流程
随机推荐
Image 24 bit depth to 8 bit depth
Computer graduation design PHP sports goods online sales system website
Typescript official website tutorial
2022-2028 global plasmid DNA cdmo industry research and trend analysis report
2022-2028 global physiotherapy clinic industry research and trend analysis report
图像24位深度转8位深度
042. (2.11) do it when it's time to do it
How to analyze the rising and falling rules of London gold trend chart
PHP MySQL where clause
Theoretical description of linear equations and summary of methods for solving linear equations by eigen
12、 Service management
NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线
Count the number of pixel values in the image
Redis core technology and practice - learning notes (VII) sentinel mechanism
Graduation summary
[untitled]
Coordinate layer conversion tool (video)
[combinatorics] generating function (property summary | important generating function)*
041. (2.10) talk about manpower outsourcing
[combinatorics] exponential generating function (example 2 of solving multiple set permutation with exponential generating function)