Java connection mysql database method and code (jdbc)

The compiler uses IDEA

My related blog:
The method of connecting to the mysql database in the java code program and
the concurrent locking problem of the code mysql database, java code

1. Use the MySQL jdbc connector mysql-connector-java.jar.

1. First download the mysql-connector-java.jar package from the mysql official website to the local.
Be careful here to match your local mysql database version!
insert image description here
Download the corresponding compressed package and decompress it locally to proceed to the next step.

2. Open your own java file and create a lib package under the source folder, as follows.

Regarding why you need to create a new lib folder and import files here, I believe that friends will know the reason soon,
because this is for the convenience of sending the files to others, and the dependent mysql-connector-java.jar is gone (if you If you place it in libraries!!) , you can still have this file after packaging by creating a new folder yourself.
insert image description here
Find the local mysql-connector-java.jar file, copy and paste it into the lib folder, and click OK.
insert image description here
insert image description here
As shown above.
3. Configure related dependencies, there are two ways here! !
The first way: directly set the lib folder as library
insert image description here
and click ok! !

The second way:
first right-click the project folder, the following window pops up, and click Open Module Settings.
insert image description here
Enter the following interface, click the + sign
insert image description here
to pop up the option, select the Jars or Directories option, and import the lib folder of mysql-connector-java.jar after the pop-up, and click OK.
insert image description here
insert image description here
After successful application, check the file, click apply, OK to use normally.
insert image description here
4. The database connection code sample is as follows

package sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Conn {
    
     // 创建类Conn
    Connection con; // 声明Connection对象
    public static String user;
    public static  String password;
    public Connection getConnection() {
    
     // 建立返回值为Connection的方法
        try {
    
     // 加载数据库驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("数据库驱动加载成功");
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        }
        user = "root";//数据库登录名
        password = "root";//密码
        try {
    
     // 通过访问数据库的URL获取数据库连接对象
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=gbk", user, password);
            System.out.println("数据库连接成功");
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return con; // 按方法要求返回一个Connection对象
    }
    public static void main(String[] args) {
    
     // 主方法,测试连接
        Conn c = new Conn(); // 创建本类对象
        c.getConnection(); // 调用连接数据库的方法
    }
}

If the above is not easy to understand, look at the following code, which is more concise:

package Main;

import java.sql.*;

public class JDBC {
    
    
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
    
    
//        1.加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
//        2.用户信息和url
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=true";
        String username="root";
        String password="root";
//        3.连接成功,数据库对象 Connection
        Connection connection = DriverManager.getConnection(url,username,password);
//        4.执行SQL对象Statement,执行SQL的对象
        Statement statement = connection.createStatement();
//        5.执行SQL的对象去执行SQL,返回结果集
        String sql = "SELECT *FROM studentinfo;";
        ResultSet resultSet = statement.executeQuery(sql);
        while(resultSet.next()){
    
    
            System.out.println("SNo="+resultSet.getString("SNo"));
            System.out.println("SName="+resultSet.getString("SName"));
            System.out.println("Birth="+resultSet.getString("Birth"));
            System.out.println("SPNo="+resultSet.getString("SPNo"));
            System.out.println("Major="+resultSet.getString("Major"));
            System.out.println("Grade="+resultSet.getString("Grade"));
            System.out.println("SInstructor="+resultSet.getString("SInstructor"));
            System.out.println("SPwd="+resultSet.getString("SPwd"));
        }
//        6.释放连接
        resultSet.close();
        statement.close();
        connection.close();
    }
}

result
insert image description here

Code explanation:
Connection: Connection object, used to connect to the database.
The official document has the following explanation of the official explanation and the methods involved
insert image description here
Class.forName("com.mysql.cj.jdbc.Driver"); in order to load the jdbc driver. You can successfully connect to the mysql database without using this statement. There is a good article about it here
Curious I found this thing in mysql-connector-java.jar! !
insert image description here
The following is the source code in the Driver. It can be seen from this that its function is to register the Driver.
insert image description here

 con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=gbk", user, password);

Here call the DriverManager.getConnection method to connect to the database, the format is as above.
localhost: Specify as local.
3306: It is the database port.
test1: the name of the database to be connected.
useUnicode=true&characterEncoding=gbk: To add encoding and decoding format requirements.
useSSL: secure connection.
user and password: the database user name and password.

After completing the above operations, you can successfully connect to the database. The last main class is used for testing, it does not need to be kept in your java file, just create this class in the file that needs to connect to the database.

Talk is cheap, show me the code! —— Xinhuo Studio!

Guess you like

Origin blog.csdn.net/qq_52050769/article/details/118095034