当前位置:网站首页>JDBC (IV)
JDBC (IV)
2022-06-25 04:44:00 【hercu1iz】
- Concept Overview
## JDBC:
1. Concept : Java Database Connectivity. java Database connection ,java Language operation database .
* JDBC The essence : official (sun company ) Defined set of operations all Relational type Database rules , 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 .
2. Quick start :
* step :
1. Import driver jar package mysql-connector-java-5.1.37-bin.jar
1. Copy mysql-connector-java-5.1.37-bin.jar To the project libs Under the table of contents
2. Right click -->Add as Library
2. Registration drive
3. Get database connection object Connection
4. Definition sql
5. Access to perform sql Object of statement Statement
6. perform sql, Accept the return result
7. Processing results
8. Release resources
* Code implementation :
//1. Import driver jar package
//2. Registration drive
Class.forName("com.mysql.jdbc.Driver");
//3. Get database connection object
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "root");
//4. Definition sql sentence
String sql = "UPDATE account set balance = 500 where id = 1";
//5. Access to perform sql The object of statement
Statement stmt = conn.createStatement();
//6. perform sql
int conunt = stmt.executeUpdate(sql);
//7. Processing results
System.out.println(conunt);
//8. Release resources
stmt.close();
conn.close();
3. Explain the objects in detail
1. DriverManager: Drive management objects
* function :
1. Registration drive : Tell the program which database driver to use jar
static void registerDriver(Driver driver) : Register with given driver DriverManager .
Write code using : Class.forName("com.mysql.jdbc.Driver");
Discover by looking at the source code : 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
* user: user name
* password: password
2. Connection: Database connection object
1. function :
1. Access to perform sql The object of
* Statement createStatement()
* PreparedStatement prepareStatement(String sql)
2. Manage affairs :
* Open transaction : setAutoCommit(boolean autoCommit): Call this method to set parameters false, That is, start the transaction .
* Commit transaction : commit()
* Roll back the transaction : rollback()
3. Statement: perform SQL The object of
1. perform SQL
1. boolean execute(String sql): You can do whatever you want sql ( understand )
2. int executeUpdate(String sql): perform 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 Is successful , conversely , Failure .
3. ResultSet executeQuery(String sql): perform DQL(select) sentence .
2. practice : Additions and deletions
Template code :
package cn.itcast.jdbc;
import com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class jdbcDemo2 {
public static void main(String[] args) {
Statement stmt = null;
Connection conn = null;
try {
//1. Registration drive
Class.forName("com.mysql.jdbc.Driver");
//2. Definition sql
String sql = "insert into account values(2,'zhang3',3000)";
//3. obtain Connection object
conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");
//4. Access to perform sql object statement
stmt = conn.createStatement();
//5. perform sql
int count = stmt.executeUpdate(sql);
System.out.println(count);
if (count > 0){
System.out.println("successful");
}else{
System.out.println("fail");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
// Avoid null pointer release exceptions
if (stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
4. ResultSet: Result set object , Encapsulate query results .
* 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 getInit()
* Parameters :
1. int: Represents the number of the column , from 1 Start .
2. String: Represents the name of the column .
* Be careful :
* Use steps :
1. Move the cursor down one line
2. Judge whether there is data
3. get data
5. PreparedStatement: perform SQL object
1. SQL Injection problem : In splicing sql when , Somewhat sql Special keywords participate in string splicing . It will cause safety problems .
2. solve sql Injection problem : Use PreparedStatement Object to solve .
3. precompile SQL: Parameters use ? As Place holder .
4. step :
1. Import driver jar package mysql-connector-java-5.1.37-bin.jar
1. Copy mysql-connector-java-5.1.37-bin.jar To the project libs Under the table of contents
2. Right click -->Add as Library
2. Registration drive
3. Get database connection object Connection
4. Definition sql
* Be careful : sql Parameter usage of ? As placeholder . Such as : select * from user where user = ? and passwd = ?;
5. Access to perform sql Object of statement : PreparedStatement Connection.preparedStatement(String sql);
6. to ? assignment :
* Method : setXXX( Parameters 1, Parameters 2)
* Parameters 1: ? Location number of , from 1 Start .
* Parameters 2: ? Value .
7. perform sql, Accept the return result , There is no need to pass on sql sentence
8. Processing results
9. Release resources
5. Be careful : It will be used later PreparedStatement To complete all operations of addition, deletion, modification and query
1. Can prevent SQL Inject
2. More efficient
## extract JDBC Tool class : JDBCUtils
* Purpose : Simplify writing
* analysis :
1. Registration drivers also extract
2. Extract a method to get the connection object
* demand : Don't want to pass parameters ( trouble ), We also need to ensure the universality of tool class .
* solve : The configuration file
jdbc.properties
url=
user=
password=
3. Extract a method to release resources
* Code implementation :
import com.mysql.jdbc.Driver;
import java.sql.*;
public class jdbcDemo4 {
public static void main(String[] args) {
Statement stmt = null;
Connection conn = null;
ResultSet rs =null;
try {
//1. Registration drive
Class.forName("com.mysql.jdbc.Driver");
//2. Definition sql
String sql = "select * from account";
//3. obtain Connection object
conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");
//4. Access to perform sql object statement
stmt = conn.createStatement();
//5. perform sql
rs = stmt.executeQuery(sql);
rs.next();
int id = rs.getInt(1);
String name = rs.getString("name");
int balance = rs.getInt(3);
System.out.println(id+ name+ balance);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
// Avoid null pointer release exceptions
if (rs !=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
* practice
* demand :
1. Enter the user name and password through the keyboard
2. Determine whether the user has successfully logged in
package cn.itcast.jdbc;
import cn.itcast.utils.JDBCUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
/**
* practice
* * demand :
* 1. Enter the user name and password through the keyboard
* 2. Determine whether the user has successfully logged in
*/
* step :
1. Create database tables
create table user(
id int primary key auto_increment,
username varchar(32),
password varchar(32));
2. Realization
public class JDBCDemo9 {
public static void main(String[] args) {
//1. Keyboard Entry , Accept user name and password
Scanner sc = new Scanner(System.in);
System.out.println(" Please enter a user name ");
String username = sc.nextLine();
System.out.println(" Please input a password ");
String password = sc.nextLine();
//2. Calling method
boolean flag = new JDBCDemo9().login(username, password);
//3. Judge the result
if (flag){
System.out.println("successful");
}else{
System.out.println("fail...");
}
}
// Login method
public boolean login(String username, String password){
if(username == null || password == null){
return false;
}
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
// Connect to database , Judge success
//1. For a link
try {
conn = JDBCUtils.getConnection();
//2. Definition sql
String sql = "select * from user where username = '"+ username +"' and password = '"+password+"'";
//3. Access to perform sql The object of
stmt = conn.createStatement();
//4. perform sql
rs = stmt.executeQuery(sql);
//5. Judge
return rs.next();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(rs,stmt,conn);
}
return false;
}
}
## JDBC Control the transaction :
1. Business : A business operation with multiple steps . If the business operation is managed by a transaction , Then these multiple steps will either succeed at the same time , Or fail at the same time .
2、 operation :
1. Open transaction
2. Commit transaction
3. Roll back the transaction
3. Use Connection Object to manage affairs
* Open transaction : setAutoCommit(boolean autoCommit): Call this method to set parameters false, That is, start the transaction .
* In execution sql Before opening the transaction
* Commit transaction : commit()
* When all sql All commit transactions are completed
* Roll back the transaction : rollback()
* stay catch Rollback transaction
## Database connection pool
1. Concept : It's actually a container ( aggregate ), Container for database connection .
When the system is initialized , Easy to create , Some connection objects will be applied for in easy , When the user comes to access the database , Get the connection object from the container , After the user visits , The connection object is returned to the container .
2. benefits :
1. Saving resource
2. Efficient user access
3. Realization :
1. Standard interface : DataSource javax.sql Under bag
1. Method :
* Get the connection : getConnection()
* Return connection : Connection.close(). If the connection object Connection It's taken from the connection pool , So called Connection.close() Method , The connection will no longer be closed , But return the connection .
2. Generally we don't realize it , There are database vendors to implement .
1. C3P0: Database connection pool technology
2. Druid: Database connection pool implementation technology , Provided by Alibaba
4. C3P0: Database connection pool
* step :
1. Import jar package : ( Two )c3p0-0.9.5.2.jar、mchange-commons-java-0.2.12.jar
* Be careful : Don't forget to import database drivers jar package
2. Define configuration file :
* name : c3p0.properties Or c3p0-config.xml
* route : Put the document directly in src Under the directory .
3. Create core objects Database connection pool object ComboPooledDataSource
4. Get the connection : getConnection
5. Druid: Database connection pool implementation technology , Provided by Alibaba
1. step :
1. Import jar package druid-1.0.9.jar
* Be careful : Don't forget to import database drivers jar package
2. Define configuration file :
* yes properties Formal
* You can call it anything , It can be placed in any directory
3. Load profile .Properties
4. Get database connection pool object : Get through the factory class DruidDataSourceFactory
5. Get the connection : getConnection
2. Define a class
1. Define a class JDBCUtils
2. Provide static code block loading configuration file , Initialize connection pool object
3. Provide methods
1. Get the connection method : Get the connection through the database connection pool
2. Release resources
3. How to get the connection pool
## Spring JDBC
* Spring Frame pair JDBC Simple encapsulation . Provides a JDBCTemplate Object simplification JDBC Development of
* step :
1. Import jar package
2. establish JDBCTemplate object . Depending on the data source DataSource
* JdbcTemplate template = new JdbcTemplate(ds);
3. call JdbcTemplate To complete CRUD The operation of
* update(): perform DML sentence . Add, delete, or change statements .
* queryForMap(): Query results encapsulate the result set as map aggregate , Name as key, Take the value as value, Encapsulate this record as a map aggregate
* Be careful : The result set length of this method query can only be 1
* queryForList(): Query results encapsulate the results as List aggregate
* Be careful : Encapsulate each record as a Map aggregate , then Map The collection is loaded into List Collection .
* query(): Query results , Encapsulate the result as JavaBean object
* query Parameters of : RowMapper
* Generally we use BeanPropertyRowMapper Implementation class . Can complete data to JavaBean Automatic encapsulation of .
* new BeanPropertyRowMapper< type >( type .class)
* queryForObject: Query results , Encapsulate the results as objects
* Commonly used in Aggregate functions Query for
边栏推荐
- 【FLink】access closed classloader classloader.check-leaked-classloader
- Separation of storage and computing in Dahua cloud native database
- Musk released humanoid robot. Why is AI significant to musk?
- Solution of gbase 8s livelock and deadlock
- OOP栈类模板(模板+DS)
- Structure syntaxique des procédures stockées gbase 8S
- OpenSea PHP开发包
- [esp32 learning path 6 - Flash encryption]
- [Flink] problems and solutions of the continuous growth of checkpoint size in rocksdb incremental mode
- GBase 8s的封锁技术的基本介绍
猜你喜欢

30岁了开始自学编程,家里比较困难还来得及吗?

《牛客刷verilog》Part I Verilog快速入门

CTF_ Web: deserialization of learning notes (II) CTF classic test questions from shallow to deep

GBASE 8s 索引R树

Concat() in JS

Machine learning deep learning -- Vectorization

Join() in JSZ

Chapter IX app project test (2) test tools

执行SQL响应比较慢,你有哪些排查思路?

领导:谁再用 Redis 过期监听实现关闭订单,立马滚蛋!
随机推荐
php封装curl发送get、post请求方法,并使用
为什么TCP握手刚刚好是3次呢?
Structure syntaxique des procédures stockées gbase 8S
Solution of gbase 8s livelock and deadlock
GBASE 8s中DELIMIDENT环境变量的使用
初识 Flutter 的绘图组件 — CustomPaint
Paper notes: multi label learning ESMC (I don't understand it, but I haven't written it yet, so I'll put it here for a place temporarily)
GBASE 8S内存管理
php开发支付宝支付功能之扫码支付流程图
Sleep more, you can lose weight. According to the latest research from the University of Chicago, sleeping more than 1 hour a day is equivalent to eating less than one fried chicken leg
Chapter IX app project test (2) test tools
leetcode1221. 分割平衡字符串
Mongodb cluster
jsz中的join()
写shell脚本报错总结
Gbase 8s index R tree
CTF_ Web: how to recognize and evaluate a regular expression
cannot import name ‘escape’ from ‘jinja2’【成功解决】
Huawei Hongmeng development lesson 4
Gbase 8s stored procedure flow control