jdbc directly connected to the database

1. jdbc connects to the database

1.1. Steps

  • Load the database driver

    • mysql driver: com.mysql.jdbc.Driver
    • oracle驱动:oracle.jdbc.driver.OracleDriver
    Class.forName("com.mysql.jdbc.Driver")
    
  • get connection

    • mysql: jdbc: mysql://mysql host IP: port number (usually 3306) / database name? userUnicode=true&characterEncoding=utf8&useSSL=false
    • oracle: jdbc:oracle:thin:@host IP:port number (usually 1521):database name
    DriverManager.getConnection(url, user, password)
    
  • execute sql

    Use precompiled PreparedStatement to prevent sql injection problems

  • get result set

  • close connection

    Don't forget to close the connection

1.2. Example code

package org.jdbc.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtil {
    
    
    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static {
    
    
        try {
    
    
            InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(in);
            driver = properties.getProperty("jdbc.driver");
            url = properties.getProperty("jdbc.url");
            username = properties.getProperty("jdbc.username");
            password = properties.getProperty("jdbc.password");

            // 加载驱动,只需要加载一次
            Class.forName(driver);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
    
    
        return DriverManager.getConnection(url, username, password);
    }

    /**
     * 释放连接
     * @param conn
     * @param stat
     * @param rs
     */
    public static void release(Connection conn, Statement stat, ResultSet rs){
    
    
        try {
    
    
            if(rs!=null) {
    
    
                rs.close();
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }

        try {
    
    
            if(stat != null) {
    
    
                stat.close();
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }

        try {
    
    
            if(conn != null) {
    
    
                conn.close();
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

}

jdbc.properties file

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mine?userUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username = root
jdbc.password = root

2. Affairs

2.1. Overview

Either all succeed or both fail

ACID principles

  1. atomicity

    A transaction is an indivisible unit of work that either succeeds or both fail

  2. consistency

    total unchanged

  3. isolation

    Multiple processes do not interfere with each other, and the operations and data used within a transaction are isolated from other concurrent transactions

  4. Persistence

    Once a transaction is committed, itChanges to data in the database are permanentYes, subsequent other operations and database failures should not have any effect on it,

    persisted to the database

Isolation question:

Dirty read: A transaction reads another uncommitted transaction

Non-repeatable read: In the same transaction, the data in the table is repeatedly read, and the table data has changed

False reading: In the same transaction, the data inserted by others is read, resulting in inconsistent reading results

2.2. Sample code:

@Test
    public void testTransaction(){
    
    
        Connection conn = null;
        PreparedStatement ptst = null;

        try {
    
    
            // 获取连接
            conn = JdbcUtil.getConnection();
            conn.setAutoCommit(false);  // 关闭自动提交,开启事务
            String sql1 = "update account set money = money - 100 where name='A'";
            // 预编译sql
            ptst = conn.prepareStatement(sql1);
            ptst.executeUpdate();

            // 测试事务
            int x = 1 / 0;

            String sql2 = "update account set money = money + 100 where name='B'";
            ptst = conn.prepareStatement(sql2);
            ptst.executeUpdate();

            // 业务完毕,提交事务
            conn.commit();
            System.out.println("成功");
        } catch (SQLException e) {
    
    
            // 出现异常,默认会自动调用rollback,回滚数据
            e.printStackTrace();
        } finally {
    
    
            JdbcUtil.release(conn, ptst, null);
        }
    }

Guess you like

Origin blog.csdn.net/Tiny_Cao/article/details/120557441