Six-step example code for JDBC connection (connecting to MySQL)

Six-step example code for JDBC connection (connecting to MySQL)

Six steps of JDBC:

1. Register the driver

2. Get a database connection

3. Get the operation object of the database

4. Execute SQL statements

5. Process the query result set (if there is no select statement in the executed statement, this step does not need to be written)

6. Close resources

Step 1: Register the driver

//Exceptions must be handled //The code may vary depending on the version. The old version is DriverManager.register(new com.mysql.jdbc.Driver());
//or Class.forName("com.mysql.jdbc.Driver");
 
 
//The new version is DriverManager.register(new com.mysql.cj.jdbc.Driver());
//or Class.forName("com.mysql.cj.jdbc.Driver");

Step 2: Get a database connection

//Because we need to perform try..catch and close the resource, we write it outside try and assign it a value of null Connection conn = null;
...
//The return value is Connection. The url writing of the old and new versions is also different. // jdbc:mysql://localhost:3306/t_use is the same as before. Change t_use to your own database name. //Old version conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t_use","user name","password");
 
 
//New versionconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t_use?serverTimezone=GMT%2B8","user name","password");

Step 3: Get the database operation object

//This is the same Connection as before Statement st = null;
...
//This way the object is created st = conn.createStatement();

Step 4: Execute SQL statements

//Write the sql statement in quotation marks String sql = " ";
//Use the object just created to access this sql statement //There is something else to say here. If it is not a select statement, use the following one. The return value is an int, so there is no need for step 5. st.executeUpdate(sql);
 
//If the sql statement is select, you need to use the following statement, and you also need to define a ResultSet object to receive this value //Then proceed to step 5 ResultSet rs = null; //Same as Connection rs = st.executeQuery(sql);

Step 5: Process the query result set

//This is only processed by the select statement, not only can getString but also getInt, etc. while (rs.next()) {
    String str = rs.getString("The name of the field to be output");
}

Step 6: Close the resource

//The first five steps are all performed in try, and the sixth step is performed in finally //Close the connection if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
 
            if (st != null) {
                try {
                    st.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
 
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

There is also a sequence for closing connections: first close the ResultSet, then the Statement object, and finally the Connection object.

Complete code

package jdbc.com;
import com.mysql.cj.protocol.Resultset;
 
import java.sql.*;
public class Test02 {
    public static void main(String[] args) {
 
        Connection conn = null;
        Statement st = null;
        ResultSet rt = null;
        try {
            //Register the connection (can be written in one line)
            //com.mysql.cj.jdbc.Driver Driver = new com.mysql.cj.jdbc.Driver();
            DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
            //Get database connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/liu2?serverTimezone=GMT%2B8","user name","password");
            //Get the database operation object st = conn.createStatement();
            //Execute sql statement String sql = "select ename,sal from emp order by sal desc";
            rt = st.executeQuery(sql);
            //Processing query statements while (rt.next()) {
               String ename = rt.getString("ename");
               String sal = rt.getString("sal");
               System.out.println(ename + "," + sal);
           }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //Close the connection if (rt != null) {
                try {
                    rt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
 
            if (st != null) {
                try {
                    st.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
 
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
 
 
        }
    }
}

Finally, if you want to pass in a value, it may cause SQL injection. The solution is to change Statement into PreparedStatement to avoid SQL injection problems. However, the code of the third and fourth steps is slightly different, so I will not go into details. .

Summarize

This is the end of this article about JDBC connection (connection with MySQL). For more relevant JDBC and MySQL connection content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A complete explanation of MySQL JDBC programming in five steps
  • MySQL database JDBC programming detailed process
  • Detailed steps for implementing JDBC in MySQL
  • Detailed explanation of Java using JDBC to connect to MySQL database
  • JDBC connects to MySQL and implements fuzzy query
  • MySQL database JDBC programming (Java connects to MySQL)
  • Detailed steps for Java to connect to MySQL 8.0 JDBC (IDEA version)
  • Example analysis of accessing MySql public methods based on JDBC
  • JDBC connection MYSQL step by step explanation

<<:  CSS to achieve the effect of rotating flip card animation

>>:  Summary of several common methods of JavaScript arrays

Recommend

Docker configuration Alibaba Cloud image acceleration pull implementation

Today I used docker to pull the image, but the sp...

Full HTML of the upload form with image preview

The upload form with image preview function, the ...

Some common properties of CSS

CSS background: background:#00ffee; //Set the back...

How to explain TypeScript generics in a simple way

Table of contents Overview What are Generics Buil...

Gallery function implemented by native Js

Table of contents The first The second Native Js ...

FlashFXP ftp client software registration cracking method

The download address of FlashFXP is: https://www....

Navicat for MySql Visual Import CSV File

This article shares the specific code of Navicat ...

Conditional comments to determine the browser (IE series)

<!--[if IE 6]> Only IE6 can recognize <![...

Detailed description of common events and methods of html text

Event Description onactivate: Fired when the objec...

A simple example of MySQL joint table query

MySql uses joined table queries, which may be dif...