其他分享
首页 > 其他分享> > web基础6-JDBC复习

web基础6-JDBC复习

作者:互联网

web基础6-JDBC复习

一、什么是JDBC

驱动:声卡、显卡、数据库

没有驱动,应用程序无法直达数据库。

我们的程序会通过数据库驱动,和数据库打交道!

但即使有了数据库驱动了,不同的数据库有不同的数据库驱动,那我们有10套数据库,岂不是要10套程序?JDBC就应运诞生了。

架构上:没有什么是加一层不能做的。

oracle公司为了简化 开发人员的操作,提供了一个(java操作数据库的)规范,实际上一套接口,俗称JDBC,这些规范的实现由具体的厂商去做~

对开发人员来说,只用掌握jdbc接口的操作即可,和JDBC打交道。

二、JDBC操作

2.1 导入依赖

需要导入3个包:

java.jar

javax.jar

还需要导入一个数据库驱动包:mysql-connecter-java.jar

或者通过maven导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.happy</groupId>
    <artifactId>javaweb-jdbc</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
    </dependencies>
</project>

2.2 实验环境搭建

INSERT INTO users(`id`,`name`,`password`,`email`,`birthday`) VALUES(NULL,'张三','123456','zs@qq.com','1987-02-18'),
(NULL,'李四','123456','zs@qq.com','1987-02-18'),
(NULL,'王五','123456','ww@qq.com','1987-02-18'),
(NULL,'赵六','123456','zl@qq.com','1987-02-18')

2.3 JDBC固定步骤

  1. 数据库配置4大属性

    driver,url,username,password

  2. 加载驱动

  3. 连接数据库,代表数据库

  4. 向数据库发送SQL对象statement:CRUD

  5. 编写SQL(根据业务,不同sql)

  6. 关闭连接

2.4 代码

CRUD

package com.happy.jdbc;

import com.happy.utils.JDBCUtils;
import jdk.nashorn.internal.scripts.JD;
import org.junit.Test;

import java.sql.*;

public class JDBCtest {

    public static void main(String[] args) throws ClassNotFoundException {

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
//            2.utils获取connection
            connection = JDBCUtils.getConnection();
//            3.向数据库发送sql的对象statement
            statement = connection.createStatement();
//            4.编写sql
            String sql = "select * from users;";
//            5.执行查询sql,返回一个ResultSet
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                String name = resultSet.getString("name");
                String password = resultSet.getString("password");
                System.out.println(name + ":" + password);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
//            6.关闭连接
            JDBCUtils.release(connection, statement, resultSet);
        }
    }

    @Test
    public void delete() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement("delete from users where id=?");
            preparedStatement.setInt(1, 3);
//            result 为受影响的行数
            int result = preparedStatement.executeUpdate();
            if (result > 0) {
                System.out.println("删除成功行数:" + result);
            } else {
                System.out.println("删除失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(connection, preparedStatement, null);
        }
    }

    @Test
    public void insert() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement("insert into users(`id`,`name`,`password`,`email`,`birthday`) values(null,?,?,?,?)");
            preparedStatement.setString(1, "happy");
            preparedStatement.setString(2, "666666");
            preparedStatement.setString(3, "happy@qq.com");
            long l = System.currentTimeMillis();
            preparedStatement.setDate(4, new Date(l));
            int result = preparedStatement.executeUpdate();
            if (result > 0) {
                System.out.println("插入成功行数:" + result);
            } else {
                System.out.println("插入失败");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("插入失败");
        } finally {
            JDBCUtils.release(connection, preparedStatement, null);
        }
    }

    @Test
    public void update() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement("update users set email=? where name=?");
            preparedStatement.setString(1, "happy1234@qq.com");
            preparedStatement.setString(2, "happy");
            int result = preparedStatement.executeUpdate();
            if (result > 0) {
                System.out.println("更新成功行数:" + result);
            } else {
                System.out.println("更新失败");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("更新失败");
        } finally {
            JDBCUtils.release(connection, preparedStatement, null);
        }
    }
}

JDBCUtils.java

package com.happy.utils;

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

public class JDBCUtils {
    static String driver;
    static String url;
    static String username;
    static String pwd;

    static {

        Properties properties = new Properties();
        InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        // properties.load(in);
        try {
            properties.load(new InputStreamReader(in, "UTF-8")); // 解决中文乱码问题
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = properties.get("driver").toString();
        url = properties.get("url").toString();
        username = properties.get("username").toString();
        pwd = properties.get("password").toString();


//        driver = "com.mysql.cj.jdbc.Driver";
////        后面请求参数解决中文乱码
//        url = "jdbc:mysql://l ocalhost:3306/jdbc?userUnicode=true&characterEncoding=utf-8";
//        username = "root";
//        pwd = "1987518g";
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(url, username, pwd);
        return connection;
    }

    public static void release(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

JDBC.properties

driver =com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/jdbc?userUnicode=true&characterEncoding=utf-8
username = root
password = 1987518g

三、JDBC事务

事务:要么都成功,要么都失败!

3.1 事务的ACID原则

ACID原则:保证数据安全

A: 原子性。不可分割,一起失败要么一起成功

C: 一致性。前后逻辑一致,如转账前后总额不变

I: 隔离性。一个事务和另外一个事务隔离

D: 持久性(durability)一旦提交,不可回退。

Junit单元测试
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
开启事务 setAutocommit(false)
事务提交 commit()
事务回滚 rollback()
事务关闭

转账:
    A:1000
    B:1000

3.2 JDBC事务的操作

模拟事务:转账

package com.happy.jdbc;

import com.happy.utils.JDBCUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class TxTest {

    @Test
    public void test(){
        transfer(11,22,200);
    }

    public void transfer(int accountA,int accountB,int amount){

        Connection connection=null;
        PreparedStatement preparedStatement=null;
        try{
            connection = JDBCUtils.getConnection();
            String sql="update account set money=money+? where accountId=?";
            preparedStatement= connection.prepareStatement(sql);
//            start transaction,相当于开启事务
            connection.setAutoCommit(false);
            update(accountA,amount,preparedStatement);
//            int i=1/0;
            update(accountB,-amount,preparedStatement);
            connection.commit();
        } catch (SQLException e) {
//            失败则都失败,进行回滚
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }

        }finally {
            JDBCUtils.release(connection,preparedStatement,null);
        }

    }

    public void update(int accountId,int amount,PreparedStatement preparedStatement){

        try {

            preparedStatement.setInt(2,accountId);
            preparedStatement.setInt(1,amount);
            preparedStatement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

标签:web,JDBC,java,复习,JDBCUtils,connection,preparedStatement,import,null
来源: https://www.cnblogs.com/happycarpediem/p/16200065.html