当前位置:网站首页>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
边栏推荐
- 4. Find the median of two positive arrays
- Discussion on related configuration of thread pool
- After marriage
- [staff] pitch representation (treble clef | C3 60 ~ B3 71 pitch representation | C4 72 pitch representation | C5 84 pitch representation)
- LFM信号加噪、时频分析、滤波
- Learning notes of software testing -- theoretical knowledge of software testing
- Start a business
- How does proxy IP participate in the direct battle between web crawlers and anti crawlers
- The basic steps of using information theory to deal with scientific problems are
- 2022-2028 global encryption software industry research and trend analysis report
猜你喜欢
Remote connection to MySQL under windows and Linux system
Xiaomi, a young engineer, was just going to make soy sauce
Pychart creates new projects & loads faster & fonts larger & changes appearance
Feature query of hypergraph iserver rest Service
[learn C and fly] 3day Chapter 2 program in C language (exercise 2.3 calculate piecewise functions)
PHP notes - use Smarty to set public pages (include, if, else, variable settings)
LFM signal denoising, time-frequency analysis, filtering
Mongodb base de données non relationnelle
Coordinatorlayout + tablayout + viewpager2 (there is another recyclerview nested inside), and the sliding conflict of recyclerview is solved
2022-2028 global human internal visualization system industry research and trend analysis report
随机推荐
Remote connection to MySQL under windows and Linux system
es面試題
Ten minutes will take you in-depth understanding of multithreading - multithreaded teamwork: synchronous control
SAP ui5 beginner tutorial 19 - SAP ui5 data types and complex data binding
Realize the code scanning function of a custom layout
Render header usage of El table
[learn C and fly] 3day Chapter 2 program in C language (exercise 2.3 calculate piecewise functions)
MongoDB非关系型数据库
2022-2028 global aluminum beverage can coating industry research and trend analysis report
Systemserver service and servicemanager service analysis
After marriage
A list of job levels and salaries in common Internet companies. Those who have conditions must enter big factories. The salary is really high
[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
Baohong industry | 6 financial management models at different stages of life
PHP notes - use Smarty to set public pages (include, if, else, variable settings)
Analysis of FLV packaging format
[staff] restore mark (Introduction to the use of restore mark | example analysis of Metaphone mark and restore mark)
Is bone conduction earphone better than traditional earphones? The sound production principle of bone conduction earphones is popular science
超图iServer rest服务之feature查询
What is the function of the headphone driver