当前位置:网站首页>JDBC details
JDBC details
2022-07-02 02:59:00 【C. V little expert】
JDBC The essence : An officially defined set of rules for operating all relational databases , Interface . Each database manufacturer to implement this set of interface , Provide database driver .jar package . We can use this interface , To carry out .jar The implementation class in the package .
1、 Implementation steps :
① Import jar package : Create under Project lib package , take jar Copy the file to the package , Then right click the package , Select Add to Library
② Registration drive :Class.forName(“com.mysql.jdbc.Driver”); High version database “com.mysql.cj.jdbc.Driver”
③ Get database connection object
Connection c = DriverManager.getConnection(“jdbc:mysql://localhost:3306/ Database name ”,“ user name ”,“ password ”);
If it's connected to this machine , The default port number is 3306, be localhost:3306 It can be omitted , Slashes cannot be omitted .
④ Definition sql:String sql = “updect Table name set Column = value ”
⑤ Access to perform sql Object of statement Statement:Statement stmt = c.createStatement();
⑥ perform sal, Receive return result :int num = stmt.executeUpdate(sql);
⑦ Processing results :System.out.print(num);
⑧ Release resources :stmt.close(); c.close();
JDBC There is a garbled code solution when connecting to the database
url ="jdbc:mysql://localhost:3306/mydb?characterEncoding=utf8&serverTimezone=Asia/Shanghai";2、 Detailed explanation of each class :
Ⅰ、DriverManager class
effect : Drive management objects // Drag me Buy a wife
① Registration drive
Method 1 : Call directly DriverManager Class
static void registerDriver(Driver driver)//ruai Level dead special
Method 2 :Class.forName(“com.mysql.jdbc.Driver”);
take Driver Class loading near memory , There is a static code block
Its essence is execution DriverManager Methods in class static void registerDriver(Driver driver) Do driver registration .
② Get database connection // But milk can be new
static Connection
getConnection(String url,String user, String password)
url: Specify the path of the connection
url grammar :jdbc:mysql://ip( domain name ): Port number / Database name
If it is connected to the local MySQL,url The bold part in the middle can be omitted , But the slash at both ends cannot be omitted
user and password: User name and password .
Ⅱ、Connection Interface : Database connection object
Function one , Create an implementation sql The object of the class of the statement
Statement
Get the transmitter , Is used to SQL Statements are sent to the database .
PreparedStatement
prepareStatement(String sql)
Create a Transmitters , To parameterize SQL Statements are sent to the database .
Function 2 , Manage affairs
void
setAutoCommit(boolean autoCommit)
Set the parameter to fales, Open transaction
void
commit()
Commit transaction
void
rollback()
Roll back
Ⅲ、Statement Interface : perform sql Object of statement , Transmitters
boolean | execute(String sql) //A But death kei I'm special | Can execute any sql |
int | executeUpdate(String sql) | perform INSERT , UPDATE , or DELETE Statement , Returns the number of rows affected . perhaps 0, Such as SQL DDL Of the statement SQL sentence . |
ResultSet | executeQuery(String sql) // Kuairi | perform DQL Query statement ,select |
Ⅳ、ResultSet Interface : Result set object , Encapsulate query results // Swiss ra Ott
boolean next() Move the cursor down one line from the current position . The return value is false Indicates that there is no data in the row where the cursor is located T getXXX(int/String num) This method gets the contents of the line ,XXX Represents the type of data obtained , There are many kinds of overloads Object() getObject(int/String num) The ultimate solution There are probably two types of parameters :
- int: Represents the number of the column , from 1 Start , Columns such as getString(1)
- String: Represents the name of the column . Such as getString(“id”)
When using this class to traverse the contents of the database , Encapsulate the contents of the database as objects , Then load it into the collection , Ergodic set
Ⅴ、PreparedStatement Interface :Statement Subclasses of , More powerful
sql Inject : In splicing sql when , Somewhat sql Special keywords participate in string splicing , Can cause security problems .
PreparedStatement
prepareStatement(String sql)
Incoming sal Statement parameters use ? Place holder
Use PreparedStatement The process of operating the database :
① Import jar package
② Registration drive
③ Get database connection object
④ Definition sql:sql Statement parameters use ? Instead of
⑤ Use the database connection object to get the transmitter PrepareStatement(String sql): to ? The method of assignment :
setXXX( Parameter one , Parameter two )//XXX representative ? The type of
Parameter one :? The location of (int type ), from 1 Start
Parameter two :? Value , String type
setObject() The ultimate solution
⑥ perform sql, Receive return result , There is no need to pass parameters
boolean execute() //A But death kei I'm special Can execute any sql int executeUpdate() perform INSERT , UPDATE , or DELETE Statement , Returns the number of rows affected . perhaps 0, Such as SQL DDL Of the statement SQL sentence . ResultSet executeQuery() perform DQL Query statement ,select ⑦ Processing results
⑧ Release resources
边栏推荐
- Mongodb base de données non relationnelle
- The number one malware in January 2022: lokibot returned to the list, and emotet returned to the top
- [untitled]
- STM32__ 05 - PWM controlled DC motor
- STM32__05—PWM控制直流电机
- Rotating frame target detection mmrotate v0.3.1 learning model
- Connected block template and variants (4 questions in total)
- AcWing 245. Can you answer these questions (line segment tree)
- Feature query of hypergraph iserver rest Service
- Which brand of sports headset is better? Bluetooth headset suitable for sports
猜你喜欢

2022-2028 global nano abrasive industry research and trend analysis report

2022-2028 global deep sea generator controller industry research and trend analysis report
![[learn C and fly] 3day Chapter 2 program in C language (exercise 2.3 calculate piecewise functions)](/img/8e/a86a9724251718d98ce172a6a96e53.png)
[learn C and fly] 3day Chapter 2 program in C language (exercise 2.3 calculate piecewise functions)

Leetcode question brushing (10) - sequential question brushing 46 to 50
![[liuyubobobo play with leetcode algorithm interview] [00] Course Overview](/img/1c/c8cab92c74b6658c3ef608c5255f1f.png)
[liuyubobobo play with leetcode algorithm interview] [00] Course Overview

SAP ui5 beginner tutorial 19 - SAP ui5 data types and complex data binding

Pat a-1165 block reversing (25 points)
![[staff] pitch representation (bass clef | C1 36 note pitch representation | C2 48 note pitch representation | C3 60 note pitch representation)](/img/98/956d8abbccceb1aae47e25825bc63d.jpg)
[staff] pitch representation (bass clef | C1 36 note pitch representation | C2 48 note pitch representation | C3 60 note pitch representation)
![[pit] how to understand](/img/e9/f5315a03b6f3da07021f915bb18af8.jpg)
[pit] how to understand "parameter fishing"

2022-2028 global aluminum beverage can coating industry research and trend analysis report
随机推荐
Coordinatorlayout + tablayout + viewpager2 (there is another recyclerview nested inside), and the sliding conflict of recyclerview is solved
Connected block template and variants (4 questions in total)
Use usedeferredvalue for asynchronous rendering
2022 low voltage electrician test question simulation test question bank simulation test platform operation
QT实现界面跳转
Unit · elementary C # learning notes
QT使用sqllite
[question 008: what is UV in unity?]
Deployment practice and problem solving of dash application development environment based on jupyter Lab
Qualcomm platform WiFi -- P2P issue (2)
[liuyubobobo play with leetcode algorithm interview] [00] Course Overview
New programmer magazine | Li Penghui talks about open source cloud native message flow system
Jointly developed by nailing, the exclusive functions of glory tablet V7 series were officially launched
小米青年工程师,本来只是去打个酱油
AcWing 245. Can you answer these questions (line segment tree)
Leetcode question brushing (10) - sequential question brushing 46 to 50
Software testing learning notes - network knowledge
Render header usage of El table
[Chongqing Guangdong education] Sichuan University concise university chemistry · material structure part introductory reference materials
4. Find the median of two positive arrays