Java学习-JDBC

JDBC

1、数据库驱动

应用程序通过驱动连接到数据库,进而操作数据库。

2、JDBC

简化开发人员对数据库的操作,提供了一个java操作数据库的规范,俗称JDBC

对于程序猿,只需要学习JDBC提供的接口。

java.sql

javax.sql

导入数据库驱动的包: mysql-connector-java-8.0.23.jar

public class DemoJdbc01 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.连接 用户信息和url
        String url = "jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
        String username = "root";
        String password = "handhand";
        //3.连接成功,数据库对象 Connection代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);

        //4.执行SQL的对象 Statement
        Statement statement = connection.createStatement();
        //5.执行SQL的对象 去 执行SQL,可能存在结果。
        String sql = "select * from users";
        //返回的结果集
        ResultSet resultSet = statement.executeQuery(sql);

        while (resultSet.next()) {
            System.out.println("id" + resultSet.getObject("id"));
            System.out.println("name" + resultSet.getObject("name"));
            System.out.println("password" + resultSet.getObject("password"));
            System.out.println("email" + resultSet.getObject("email"));
            System.out.println("dirthday" + resultSet.getObject("dirthday"));
        }
        //6.释放连接
        resultSet.close();
        statement.close();
        connection.close();
    }
}
  • 加载驱动
  • 连接数据库 DriverManager
  • 获得执行sql的对象 Statement
  • 获得返回的结果集
  • 释放连接

URL

String url = "jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true";

//mysql -- 3306
//jdbc:mysql://主机地址:端口号/数据库名?参数1&参数2

//oracle -- 1521
//jdbc:oracle:thin:@主机地址:端口号:sid

DriverManager

Connection connection = DriverManager.getConnection(url, username, password);
//connection 代表数据库,可以做数据库的操作
//数据库设置自动提交 
connection.getAutoCommit();
//事务提交
connection.commit();
//事务回滚
connection.rollback();

Statement PrepareStatement 执行SQL的对象

statement.executeQuery();//查询操作  返回ResultSet
statement.executeUpdate(); //执行任何sql
statement.execute();//更新、插入、删除,返回受影响的行数

ResultSet 查询的结果集:封装了所有的查询结果

//在不知道列类型的情况下使用getObject,否则使用指定的类型
resultSet.getObject();
resultSet.getString();
resultSet.getInt();
resultSet.getFloat();
resultSet.getDate();
...

遍历

//移动到最前面
resultSet.beforeFirst();
//移动到最后面
resultSet.afterLast();
//移动到下一个
resultSet.next();
//移动到前一行
resultSet.previous();
//移动到指定行
resultSet.absolute(row);

释放资源

resultSet.close();
statement.close();
connection.close();

3、Statement对象

执行SQL的对象 Statement
Statement statement = connection.createStatement();

CRUD操作-create

使用executeUpdate(String sql)方法完成数据添加操作:

String sqlCreate = "INSERT INTO users VALUES ( 4, 'test', '134513', 'z13@131.com', '1995-01-01')";
int num = statement.executeUpdate(sqlCreate);
if (num > 0) {
    System.out.println("插入数据成功");
}

CRUD操作-update

使用executeUpdate(String sql)方法完成数据更新操作:

String sqlUpdate = "UPDATE users u \n" +
                "SET s.NAME = 'test02' \n" +
                "WHERE\n" +
                "\ts.id = 4";
int num = statement.executeUpdate(sqlUpdate);
if (num > 0) {
    System.out.println("更新数据成功");
}

CRUD操作-delete

使用executeUpdate(String sql)方法完成数据删除操作:

String sqlDelete="DELETE \n" +
                "FROM\n" +
                "\tusers u \n" +
                "WHERE\n" +
                "\tu.id = 4";
int num = statement.executeUpdate(sqlDelete);
if (num > 0) {
    System.out.println("插入删除成功");
}

CRUD操作-read

使用executeQuery(String sql)方法完成数据查询操作:

String sql = "select * from users";
//返回的结果集
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
}

创建utils工具类

public class JdbcUtils {
    private static String driver = null;
    private static String url = null;
    private static String name = null;
    private static String password = null;
    static {
        try {
            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(in);
            //读取properties文件定义的参数值
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            name = properties.getProperty("username");
            password = properties.getProperty("password");
            //驱动加载,只需要一次
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, name, password);
    }
    public static void release(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

调用 utils工具类

public class DemoInsert {
    public static void main(String[] args) throws SQLException {
        Connection connection = JdbcUtils.getConnection();
        Statement statement = connection.createStatement();
        String sql = "INSERT INTO users\n" +
                "VALUES\n" +
                "\t( 4, 'darj453o', '14534513', 'z13@133451.com', '1995-01-01' )";
        int i = statement.executeUpdate(sql);
        if (i>0){
            System.out.println("插入成功");
        }
        JdbcUtils.release(connection,statement,null);
    }
}

4、PreparedStatement对象

PreparedStatement 使用?占位符

防止SQL注入的本质,传递进来的参数当做字符

public class DemoUpdate {
    public static void main(String[] args) throws SQLException {
        Connection connection = JdbcUtils.getConnection();
        //区别Statement
        //使用?占位符
        String sql = "UPDATE users s \n" +
                "SET s.NAME = ?,\n" +
                "s.dirthday = ? \n" +
                "WHERE\n" +
                "\ts.id = ?";
        //预编译sql
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //手动赋值
        preparedStatement.setString(1, "test02");
        //sql.Date 数据库 java.sql.Date()
        //util.Date Java  new Date().getTime()
        preparedStatement.setDate(2, new java.sql.Date(System.currentTimeMillis()));
        preparedStatement.setInt(3, 4);
        //执行
        int i = preparedStatement.executeUpdate();
        if (i > 0) {
            System.out.println("更新成功");
        }
        JdbcUtils.release(connection, preparedStatement, null);
    }
}

5、事务

ACID原则

原子性:要哦全部完成,要么都不完成

一致性:总数不变

隔离性:多个进程互不干扰。存在以下问题

  • 脏读:一个事务读取了另一个没有提交的事务
  • 不可重复读:在同一个事务内,重复读取表中的数据,表数据发生了改变
  • 虚读:在一个事务内,读取到了别人插入的数据,导致前后读出来的结果不一致

持久性:一旦提交不可逆,持久化到数据库

6、数据库连接池

数据库执行步骤:数据库连接 --- 执行完毕 --- 释放

池化技术:准备一些预先的资源,过来就连接准备好的

连接池常用的参数

  • 最小连接数:10

  • 最大连接数: 100 业务最高承载上限

  • 等待超时:100ms

编写连接池,需要实现一个接口 DateSource

开源数据源实现

DBCP

C3P0

Druid

使用这些连接池之后,可以节省连接数据库的代码Connection connection = JdbcUtils.getConnection();

DBCP

需要用到的jar包:commons-dbcp-1.4.jar、commons-pool-1.6.jar

  • 配置文件

    #连接设置
    driverClassName=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true
    username=root
    password=handhand
    #初始化连接
    initialSize=10
    #最大连接数
    maxActive=50
    #最大空闲连接
    maxIdle=20
    #最小空闲连接
    minIdle=5
    #超时等待 以毫秒为单位
    maxWait=60000
    #JBDC驱动建立连接是负载的连接属性的格式必须为:[属性名=property;]
    #注意:“” 两个属性会被明确的传递,因此这里不需要包含他们
    connectionProperties=userUnicode=true;characterEncoding=utf8
    #指定有连接池锁创建的连接的自动提交状态(auto-commit)状态
    defaultAutoCommit=true
    #driver default 指定由连接池所创建的连接的只读(read-only)状态
    defaultReadOnly = false
    
    #driver default 指定指定由连接池所创建的连接的事物级别(TransactionIsolation)
    defaultTransactionIsolation=READ_UNCOMMITTED
    
  • 工具类

    public class JdbcUtilsDbcp {
        private static DataSource dataSource = null;
        static {
            try {
                InputStream in = JdbcUtilsDbcp.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
                Properties properties = new Properties();
                properties.load(in);
                //创建数据源 工厂模式
                dataSource = BasicDataSourceFactory.createDataSource(properties);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //获取连接
        public static Connection getConnection() throws SQLException {
            return dataSource.getConnection();
        }
        public static void release(Connection connection, Statement statement, ResultSet resultSet) {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

C3P0

需要用到的jar包:mchange-commons-java-0.2.20.jar、c3p0-0.9.5.5.jar

  • 配置文件 c3p0-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
    <!--使用默认的配置读取数据库连接池对象
     如果在代码中"ComboPooledDataSource ds = new ComboPooledDataSource()"
     这样就会使用C3P0的缺省-->
    <default-config>
        <!--  连接参数 -->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=true</property>
        <property name="user">root</property>
        <property name="password">handhand</property>
        <!-- 连接池参数 -->
        <!--初始化申请的连接数量-->
        <property name="initialPoolSize">5</property>
        <!--最大的连接数量-->
        <property name="maxPoolSize">10</property>
        <!--超时时间-->
        <property name="checkoutTimeout">60000</property>
    </default-config>
    <!--代码中"ComboPooledDataSource ds = new ComboPooledDataSource("Darker")" -->
    <named-config name="Darker">
        <!--连接参数-->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=true</property>
        <property name="user">root</property>
        <property name="password">handhand</property>

        <!--连接池参数 -->
        <property name="initialPoolSize">5</property>
        <property name="maxPoolSize">8</property>
        <property name="checkoutTimeout">60000</property>
    </named-config>
</c3p0-config>
  • 工具类
public class JdbcUtilsC3P0 {
    private static ComboPooledDataSource dataSource = null;
    static {
        try {
            //创建数据源
            dataSource = new ComboPooledDataSource("Darker");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    public static void release(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
posted @ 2021-01-25 19:25  DarkerGuo  阅读(105)  评论(0编辑  收藏  举报