Learn JDBC in 15 minutes

1. Concept understanding

Recently, I was learning the javaweb video of Kuangshen. His JDBC is very good. I wrote a technical blog to share with everyone, and at the same time, it is convenient for myself to review and use. To the point:

What is JDBC (Java DataBase Connectivity): Java connects to the database

Insert picture description hereNeed jar package support:

  • java.sql
  • javax.sql
  • The mysql-connector-java connection driver must be imported!

2. Setting up the environment before writing JDBC code:

  1. Database code:
CREATE TABLE users(
	id INT PRIMARY KEY,
	`name` VARCHAR(40),
	`password` VARCHAR(40),
	email VARCHAR(60),
	birthday DATE
); 


INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(1,'张三','123456','[email protected]','2000-01-01');

INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2,'李四','123456','[email protected]','2000-01-01');

INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3,'王五','123456','[email protected]','2000-01-01');

SELECT * FROM users;

  1. Import database dependencies
<!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
  1. Connect to the database in IDEA

Insert picture description here

Three, JDBC code steps

  1. Load the driver
  2. Connect to the database, the object represents the database
  3. Send SQL object statement to the database: CRUD
  4. Write sql (different sql according to business)
  5. Execute sql
  6. Close the connection

code show as below:

package com.xu.test;

import jdk.nashorn.internal.runtime.OptimisticReturnFilters;

import java.sql.*;

public class TestJdbc {
    
    
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
    
    
        //配置信息
        //useUnicode=true&characterEncoding=utf-8  解决中文乱码
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "root";

        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.连接数据库,该对象代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.向数据库发送sql对象 statement,PreparedStatement : CRUD
        Statement statement = connection.createStatement();

        //4.编写sql
        String sql = "select * from users";

        //5.执行查询sql,返回一个结果集
        ResultSet rs = statement.executeQuery(sql);

        while (rs.next()){
    
    
            System.out.println("id = " + rs.getObject("name"));
            System.out.println("name = " + rs.getObject("name"));
            System.out.println("password = " + rs.getObject("password"));
            System.out.println("email = " + rs.getObject("email"));
            System.out.println("birthday = " + rs.getObject("birthday"));
        }
        //6.关闭连接,释放资源,一定要做,先开后关
        rs.close();
        statement.close();
        connection.close();
    }
}

In the above code, the code used in the query is:

ResultSet rs = statement.executeQuery(sql);

However, all additions , deletions and changes are used, and the return value is the number of affected rows :

int i = statement.executeUpdate(sql);

Pre-compiled sql code:

package com.xu.test;

import java.sql.*;

public class TestJdbc2 {
    
    
    public static void main(String[] args) throws Exception {
    
    
        //配置信息
        //useUnicode=true&characterEncoding=utf-8  解决中文乱码
        String url = "jdbc:mysql://localhost:3306/jdbc";
        String username = "root";
        String password = "root";

        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2.连接数据库,该对象代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.编写sql
        String sql = "insert into users(id,name,password,email,birthday) values(?,?,?,?,?)";

        //4.预编译
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,4); //给第一个占位符? 的值赋值为4
        preparedStatement.setString(2,"徐志斌"); //给第二个占位符? 的值赋值为徐志斌
        preparedStatement.setString(3,"123456"); //给第三个占位符? 的值赋值为123456
        preparedStatement.setString(4,"[email protected]"); //给第四个占位符? 的值赋值为4
        preparedStatement.setDate(5,new Date(new java.util.Date().getTime())); //给第五个占位符? 的值赋值为5

        //5.执行sql
        int i = preparedStatement.executeUpdate();
        if (i > 0){
    
    
            System.out.println("插入成功");
        }

        //6.关闭连接,释放资源,一定要做,先开后关
        preparedStatement.close();
        connection.close();
    }
}

Four, affairs

Either all succeed or all fail.
ACID principle: to ensure data security (for example, transfer issues)

开启事务
关闭事务		commit()
事务回滚		rollback()
关闭事务

If A has transferred money, in case the system crashes, A transfers money, B does not receive. In order to prevent this from happening, the role of the transaction is proposed at this time

The code is shown below:

package com.xu.test;

import org.junit.Test;

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

public class TestJdbc3 {
    
    

    @Test
    public void test(){
    
    
        //配置信息
        //useUnicode=true&characterEncoding=utf-8  解决中文乱码
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "root";

        Connection connection = null;
        try {
    
    
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.连接数据库,该对象代表数据库
            connection = DriverManager.getConnection(url, username, password);
            //3.通知数据库开启事务,false代表开启
            connection.setAutoCommit(false);
            String sql = "update account set money = money - 100 where name = 'A'";
            connection.prepareStatement(sql).executeUpdate();
            //4.制造错误,体现事务作用
            //int i = 1 / 0;
            String sql2 = "update account set money = money + 100 where name = 'B'";
            connection.prepareStatement(sql2).executeUpdate();

            connection.commit(); //以上两条sql都执行成功,就提交事务!
            System.out.println("success");
        }catch (Exception e){
    
    
            try {
    
    
                //如果出现异常,就通知数据库回滚事务
                connection.rollback();
            } catch (SQLException e1) {
    
    
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
    
    
            try {
    
    
                connection.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_46594796/article/details/109586431