Java and database connection-JDBC (JDBC concept understanding + JDBC setup and use six steps, the author Jun Qingqing gave it, and it is a big praise!)

JDBC overview

What is the use of JDBC?

1.jdbc is used to connect our java application and database. Using jdbc allows us to read the data in the database through the java application, and can also store the data;

2. We can connect to different databases through jdbc, such as Oracle, MySQL, sql server, etc.

What is JDBC?

1. JDBC: Abbreviation for Java DataBase Connectivity, that is, java database connection. It is a Java API used to execute SQL statements, which can provide unified access to a variety of relational databases. It consists of a set of classes written in Java language and Interface composition.

2. Since the bottom layers of various databases on the market are different, and it is impossible for Java development companies to design their corresponding database connection methods according to each database on the market, therefore, Java development companies choose to design classes such as JDBC and The database connection method composed of the interface is implemented by the company of the respective database to implement the JDBC function corresponding to the database.

To sum up, the Java API provides standard interfaces for operating databases, and finally different database developers implement these standard interfaces to operate the database, and programmers only need to learn to use standard specifications.

Insert picture description here

JDBC API

JDBC API: classes and interfaces for programmers to call, integrated in the java.sql package.

Several classes and interfaces that need to be used:

DriverManager class: manage various JDBC connections;

Connection interface: connection to a specific database;

Statement interface: execute sql

PrepardeStatement interface: execute sql

ResultSet interface: receive query results

Construction and use of JDBC

To explain, I use IntelliJ IDEA 2020.2.1, mysql8 for the development tools here. Here is just a brief introduction. The different versions of the development tools and mysql do not affect the use, but there are a few small points that need to be paid attention to, the larger part There is no problem.

1 Import the database driver package

The driver package I use here is

mysql-connector-java-8.0.16.jar

You should choose the corresponding database driver package according to your database version.

The operation of importing the database driver package is as follows:

1. Create a lib directory under the project project and copy the driver package to the lib directory.

Insert picture description here

2. Find the project structure (Prioject Structure) under File—>Libraries—>click the + sign, select java—>select the jar package just imported under the project—>OK—>Apply

Insert picture description here

3. Import the database driver package is complete.

2 Load the database driver

Register the JDBC driver: This requires the initial identification of the driver, so that the communication channel with the database can be opened.

method one

Use the reflection mechanism to load the Driver class, and give the address of the class

Class.forName("com.mysql.cj.jdbc.Driver"); //这是mysql8的方式
//利用反射机制加载Driver类
try {
    
    
    Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
    
    
    e.printStackTrace();
}

Way two

Use DriverManager to register with the given driver.

DriverManger.registerDriver(new Driver());
//需要抛一个异常
try {
    
    
    DriverManager.registerDriver(new Driver());
} catch (SQLException throwables) {
    
    
    throwables.printStackTrace();
}

3 Establish a database connection

Here you need the DriverManger.getConnection() method to create a Connection object, which represents a physically connected database.

Connection connection = DriverManager.getConnection(URL,User,Passwd);
URL: jdbc:mysql://ip(127.0.0.1):端口(3306)/数据库名?characterEncoding=utf-8
	&useSSL=false&serverTimezone=UTC
	?后面的都是参数,使用&符号连接,键=值&键=值
	characterEncoding=utf8 编码格式
    useSSL=false 安全连接,现在为false
    serverTimezone=UTC 时区
User:用户名
Passwd:密码
try {
    
    
	String url = "jdbc:mysql://127.0.0.1:3306/test_db?characterEncoding=utf-8" +
					"&useSSL=false&serverTimezone=UTC";
	Connection connection = DriverManager.getConnection(url,"root","root");
} catch (SQLException throwables) {
    
    
	throwables.printStackTrace();
}

4 Send sql statement to the database

This is mainly to manipulate the database through the java program, and you need to learn two classes for sending sql statements, Statement and PrepareStatement.

Statement

Obtain the Statement object for sending SQL statements to the database

Statement st = connection.createStatement();

Two important methods

executeUpdate(String sql);
用于执行ddl(结构定义)语句和dml(增,删,改)语句
执行ddl语句返回0,执行dml返回被操作的行数,为Int型


executeQuery(String sql);
用于执行查询语句 返回一个ResultSet集合

note

使用Statement类发送sql语句需要拼接字符串,拼接字符串的方法为:双引号双加号"+内容+",如果数据库本身的字段为字符串还需要再加上单引号,即'"+内容+"',事例如下
//获得Statement对象
            Statement st = connection.createStatement();

            //发送sql语句
            String name = "小明";
            String sex = "女";
            String age = "18";
            String deptId = "3";

            int res = st.executeUpdate("" +
                    "insert into t_staff(s_name,s_sex,s_age,s_dept_id)" +
                    "values('"+name+"','"+sex+"',"+age+","+deptId+")");
            System.out.println(res);//1,被修改了一行

PrepareStatement

Obtain PrepareStatement object for sending sql statement to database

注意,prepareStatement中的参数位置使用占位符?
PrepareStatement ps = connection.PrepareStatement("sql语句,参数位置使用?");

Two important methods

executeUpdate(String sql);
用于执行ddl(结构定义)语句和dml(增,删,改)语句
执行ddl语句返回0,执行dml返回被操作的行数,为Int型


executeQuery(String sql);
用于执行查询语句 返回一个ResultSet集合

note

为sql语句设置相应参数使用
ps.set相应类型(对应参数位置,参数)
的方法
//获得PrepareStatement
            PreparedStatement ps = connection.prepareStatement(
                    "insert into t_staff(s_name,s_sex,s_age,s_dept_id)" +
                            "values(?,?,?,?)"
            );
            String name = "小暗";
            String sex = "男";
            String age = "19";
            String deptId = "2";

            ps.setString(1,name);
            ps.setString(2,sex);
            ps.setString(3,age);
            ps.setString(4,deptId);

            //发送
            int res = ps.executeUpdate();
            System.out.println(res);

5 Receive the result of the query

Here we will use the ResultSet class;

The executeQuery() method in PreparedStatement and Statement will return a ResultSet object, and the query result will be encapsulated in this object;

Use the next() method in ResultSet to get the next row of data;

Use getXXX(String name) method to get the value;

A complete query code is presented

import java.sql.*;

public class Hello {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try {
            String url = "jdbc:mysql://127.0.0.1:3306/test_db?characterEncoding=utf-8" +
                    "&useSSL=false&serverTimezone=UTC";
            Connection connection = DriverManager.getConnection(url, "root", "root");

            //获得PrepareStatement
            PreparedStatement ps = connection.prepareStatement(
                    "select * from t_staff where s_id=?"
            );
            ps.setInt(1,3);

            //发送
            ResultSet res = ps.executeQuery();
            Test test = new Test();
            while(res.next()){
                test.setS_id(res.getInt("s_id"));
                test.setS_name(res.getString("s_name"));
                test.setS_sex(res.getString("s_sex"));
                test.setS_age(res.getInt("s_age"));
                test.setS_dept_id(res.getInt("s_dept_id"));
                test.setS_money(res.getInt("s_money"));
            }
            System.out.println(test.toString());
            //Test{s_id=3, s_name='虞姬', s_sex=女, s_age=29, s_dept_id=3, s_money=2800}

            //关闭连接
            ps.close();
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
class Test{
    private int s_id;
    private String s_name;
    private String s_sex;
    private int s_age;
    private int s_dept_id;
    private int s_money;

    public void setS_id(int s_id) {
        this.s_id = s_id;
    }

    public void setS_name(String s_name) {
        this.s_name = s_name;
    }

    public void setS_sex(String s_sex) {
        this.s_sex = s_sex;
    }

    public void setS_age(int s_age) {
        this.s_age = s_age;
    }

    public void setS_dept_id(int s_dept_id) {
        this.s_dept_id = s_dept_id;
    }

    public void setS_money(int s_money) {
        this.s_money = s_money;
    }

    @Override
    public String toString() {
        return "Test{" +
                "s_id=" + s_id +
                ", s_name='" + s_name + '\'' +
                ", s_sex=" + s_sex +
                ", s_age=" + s_age +
                ", s_dept_id=" + s_dept_id +
                ", s_money=" + s_money +
                '}';
    }
}

6 Close the database connection channel

Close all connection channels with the database after each operation is completed

方法:close()

Guess you like

Origin blog.csdn.net/Lotus_dong/article/details/113097412