当前位置:网站首页>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
边栏推荐
- 3124. Word list
- The basic steps of using information theory to deal with scientific problems are
- 高并发场景下缓存处理方案
- Baohong industry | what misunderstandings should we pay attention to when diversifying investment
- 2022 low voltage electrician test question simulation test question bank simulation test platform operation
- After marriage
- Après le mariage
- CVPR 2022 | Dalian Institute of technology proposes a self calibration lighting framework for low light level image enhancement of real scenes
- 2022-2028 global manual dental cleaning equipment industry research and trend analysis report
- 【做题打卡】集成每日5题分享(第二期)
猜你喜欢

Baohong industry | four basic knowledge necessary for personal finance

2022-2028 global soft capsule manufacturing machine industry research and trend analysis report

el-table的render-header用法

QT implementation interface jump

Is bone conduction earphone better than traditional earphones? The sound production principle of bone conduction earphones is popular science

AcWing 245. Can you answer these questions (line segment tree)

2022-2028 global encryption software industry research and trend analysis report

Cache processing scheme in high concurrency scenario

创业了...

Mmsegmentation series training and reasoning their own data set (3)
随机推荐
New programmer magazine | Li Penghui talks about open source cloud native message flow system
只需简单几步 - 开始玩耍微信小程序
Mathematics in Sinorgchem: computational geometry
Set status bar color
PMP personal sprint preparation experience
Which brand of sports headset is better? Bluetooth headset suitable for sports
About DNS
Software testing learning notes - network knowledge
OSPF LSA message parsing (under update)
Qualcomm platform WiFi -- P2P issue (2)
2022 hoisting machinery command examination paper and summary of hoisting machinery command examination
Tupu software has passed CMMI5 certification| High authority and high-level certification in the international software field
LFM信号加噪、时频分析、滤波
Is bone conduction earphone better than traditional earphones? The sound production principle of bone conduction earphones is popular science
GB/T-2423. XX environmental test documents, including the latest documents
创业了...
实现一个自定义布局的扫码功能
C return multiple values getter setter queries the database and adds the list return value to the window
The capacity is upgraded again, and the new 256gb large capacity specification of Lexar rexa 2000x memory card is added
[staff] diacritical mark (ascending sign | descending sign B | double ascending sign x | double descending sign BB)