当前位置:网站首页>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
边栏推荐
- Face++ realizes face detection in the way of flow
- [staff] the direction of the symbol stem and the connecting line (the symbol stem faces | the symbol stem below the third line faces upward | the symbol stem above the third line faces downward | the
- 创业了...
- Use usedeferredvalue for asynchronous rendering
- Questions d'entrevue
- Formatting logic of SAP ui5 currency amount display
- [staff] diacritical mark (ascending sign | descending sign B | double ascending sign x | double descending sign BB)
- Which brand of running headphones is good? How many professional running headphones are recommended
- 批量检测url是否存在cdn—高准确率
- GB/T-2423. XX environmental test documents, including the latest documents
猜你喜欢

浅谈线程池相关配置

About DNS
Face++ realizes face detection in the way of flow

批量检测url是否存在cdn—高准确率

Golang configure export goprivate to pull private library code

JVM interview

Soul app released the annual report on generation Z behavior: nearly 20% of young people love shopping in the vegetable market
![[liuyubobobo play with leetcode algorithm interview] [00] Course Overview](/img/1c/c8cab92c74b6658c3ef608c5255f1f.png)
[liuyubobobo play with leetcode algorithm interview] [00] Course Overview

Baohong industry | what misunderstandings should we pay attention to when diversifying investment

Redis cluster
随机推荐
超图iServer rest服务之feature查询
2022-2028 global manual dental cleaning equipment industry research and trend analysis report
Which brand of sports headset is better? Bluetooth headset suitable for sports
Possible causes of runtime error
Qualcomm platform wifi-- WPA_ supplicant issue
2022低压电工考试题模拟考试题库模拟考试平台操作
Xiaomi, a young engineer, was just going to make soy sauce
[learn C and fly] 2day Chapter 8 pointer (practice 8.1 password unlocking)
连通块模板及变式(共4题)
Use usedeferredvalue for asynchronous rendering
Websocket + spingboot realize code scanning login
Principle of computer composition - interview questions for postgraduate entrance examination (review outline, key points and reference)
2022-2028 global military computer industry research and trend analysis report
浅谈线程池相关配置
Query word weight, search word weight calculation
tarjan2
CoordinatorLayout + TabLayout + ViewPager2(里面再嵌套一个RecyclerView),RecyclerView的滑动冲突解决
2022-2028 global soft capsule manufacturing machine industry research and trend analysis report
Jointly developed by nailing, the exclusive functions of glory tablet V7 series were officially launched
Soul app released the annual report on generation Z behavior: nearly 20% of young people love shopping in the vegetable market