java EE学习之数据库操作

jdbc开发流程

  1. 注册驱动
  2. 建立连接(Connection)
  3. 创建运行SQL的语句(Statement)
  4. 运行语句
  5. 处理运行结果(ResultSet)
  6. 释放资源

注冊驱动有三种方式:

Class.forName("com.mysql.jdbc.Driver");   // 推荐
DriverManager.registerDriver(com.mysql.jdbc.Driver);
System.setProperty(“jdbc.drivers”, “driver1:driver2”);

获取mysql链接对象

DriverManager.getConnection(url,数据库用户名,数据库密码);

设置编码

url后面加上?useUnicode=true&characterEncoding=utf8

插入数据写法

String sql = "insert into category(cid,cname) values(?,?)";
st = coon.prepareStatement(sql);
st.setString(1,"c1003");
st.setString(2,"鞋子");

executeUpdate和executeQuery

executeUpdate(String sql) 返回的是影响的行数,int类型数据,增加、删除、修改使用executeUpdate
executeQuery(String sql) 返回ResultSet对象,查询时使用,遍历使用rs.next()
execute(String sql) 可执行任何SQL语句,返回一个布尔值,表示是否返回ResultSet 。

T2.java

public class T2 {

    @Test
    public void f1() {
        
        Connection coon;
        PreparedStatement st;
        ResultSet rs = null;
        try {
            coon = JdbcUtil.getConnection();
            String sql = "insert into category(cid,cname) values(?,?)";
            
            st = coon.prepareStatement(sql);
            st.setString(1,"c1003");
            st.setString(2,"鞋子");
            int i = st.executeUpdate();
            if(i != 0) {
                System.out.print("添加成功");
            }
            
            JdbcUtil.closeResource(coon, st, rs);
        } catch (Exception e) {
            e.printStackTrace();
        }   
    }
    
}

JdbcUtil.java

public class JdbcUtil {
    
    public static Connection getConnection() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8","root","123456");
    }
    
    public static void closeResource(Connection coon,PreparedStatement st,ResultSet rs) {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
        }
        
        if(st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
        }
        
        if(coon != null) {
            try {
                coon.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
        }
        
        coon = null;
        st = null;
        rs = null;
        
    }
}

通过配置 properties 文件设置数据库连接信息

获取 properties 文件对象可以使用 ResourceBundle 工具类。

  1. 获取 ResourceBundle 对象——>getBundle("不带后缀的文件名称")
  2. 通过 ResourceBundle 获取配置信息——>getString(String key)

快捷键

通过调用方法快速生命类的对象 ——> ctrl+2 松手后按l
竖向选择 ——> alt+shift+a
快速定位问题 ——> ctrl+1
变大写 ——> ctrl+shift+x
变小写 ——> ctrl+shift+y
向上复制一行 ——> alt+ctrl+方向上键
向下复制一行 ——> ctrl+shift+方向下键
向上添加空行 ——> ctrl+shift+enter
删除一行 ——> ctrl+D
向下移动一行 ——> ctrl+方向下键
向上移动一行 ——> ctrl+方向上键

jdbc.properties

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username=root
password=123456

JdbcUtil.java 下的 getConnection 方法修改为

public class JdbcUtil2 {
    
    static final String DRIVERCLASS;
    static final String URL;
    static final String USERNAME;
    static final String PASSWORD;
    static {
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        DRIVERCLASS = bundle.getString("driverClass");
        URL = bundle.getString("url");
        USERNAME = bundle.getString("username");
        PASSWORD = bundle.getString("password");
    }
    
    static {
        try {
            Class.forName(DRIVERCLASS);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static Connection getConnection() throws Exception {
        return DriverManager.getConnection(URL,USERNAME,PASSWORD);
    }
}

通过连接池优化数据库操作

以前每一次操作都需要创建连接,用完后释放连接,用了连接池就不需要这样,想象一下,如果10000人访问站点,每一个人访问我都建立一次连接,对性能是一种负担。
连接池的原理是,在初始化的时候创建一定数量的连接,用的时候通过方法获取,不用的时候归还连接。
所有的连接池必须实现 javax.sql.Datasource 接口
获取连接池的方法:Connection getConnection()

常用的连接池:

  1. dbcp
  2. c3p0

dbcp

  • 硬编码方式
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8");
ds.setUsername("root");
ds.setPassword("123456");
Connection conn = ds.getConnection();
  • 配置文件的方式(properties文件)
Properties prop = new Properties();
prop.load(new FileInputStream("src/dbcp.properties"));;
DataSource ds = BasicDataSourceFactory.createDataSource(prop);
Connection conn = ds.getConnection();

dbcp.properties文件

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username=root
password=123456

#<!--扩展配置 了解-->
#初始化连接
initialSize=10

#最大连接数量
maxActive=50

#<!-- 最大空闲连接 -->
maxIdle=20

#<!-- 最小空闲连接 -->
minIdle=5

#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000

#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] 
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=gbk

#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true

#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=

#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED

c3p0

  • 硬编码
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8");
ds.setUser("root");
ds.setPassword("123456");
Connection conn = ds.getConnection();
  • 配置文件方式
  1. 使用properties文件方式——c3p0.properties
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
c3p0.user=root
c3p0.password=123456

配置后就可以直接使用,不需要像 dbcp 那样导入 properties 文件

ComboPooledDataSource ds = new ComboPooledDataSource();
Connection conn = ds.getConnection();
  1. c3p0-config.xml
<c3p0-config>
    <!-- 默认配置,如果没有指定则使用这个配置 -->
    <default-config>
        <!-- 基本配置 -->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf8</property>
        <property name="user">root</property>
        <property name="password">123456</property>
    
        <!--扩展配置-->
        <property name="checkoutTimeout">30000</property>
        <property name="idleConnectionTestPeriod">30</property>
        <property name="initialPoolSize">10</property>
        <property name="maxIdleTime">30</property>
        <property name="maxPoolSize">100</property>
        <property name="minPoolSize">10</property>
        <property name="maxStatements">200</property>
    </default-config> 
    
    
    <!-- 命名的配置 -->
    <named-config name="itcast">
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/xxxx</property>
        <property name="user">root</property>
        <property name="password">1234</property>
        
        
        <!-- 如果池中数据连接不够时一次增长多少个 -->
        <property name="acquireIncrement">5</property>
        <property name="initialPoolSize">20</property>
        <property name="minPoolSize">10</property>
        <property name="maxPoolSize">40</property>
        <property name="maxStatements">20</property>
        <property name="maxStatementsPerConnection">5</property>
    </named-config>
</c3p0-config> 

配置后就可以直接使用,不需要像 dbcp 那样导入 properties 文件

ComboPooledDataSource ds = new ComboPooledDataSource();
Connection conn = ds.getConnection();

当然 c3p0 支持导入配置,ComboPooledDataSource(configName),configName 对应 c3p0-config.xml 下的命名配置的 name(named-config 标签对应的 name 值),比如我们分多个环境时 就可以传入 configName 加载对应环境的配置。 如果传入的 configName 不存在或者 configName 不传,则使用默认配置

c3p0 和 dbcp 区别

dbcp 没有自动回收空闲链接的功能
c3p0 有主动回收空闲链接的功能,c3p0使用广,hibernate 和 spring 都有使用 c3p0

使用 dbutils

dbutils 是 apache 组织的一个工具类
步骤:

  1. 导入包(commons-dbutils-1.4.jar)
  2. 创建 queryrunner 类:new queryRunner(DataSource ds)
  3. 编写sql
  4. 执行sql,r使用 query() ,cud使用 update()

insert 操作

QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());
String sql = "insert into category(cid,cname) values(?,?)";
queryRunner.update(sql,"c1013","电器");

核心类

  1. QueryRunner 类,主要用于操作 sql 语句
    常用方法
    • query
    • update
  2. DbUtils 类,主要用于释放资源,控制事务
    常用方法
    • closeQuietly() 内部处理了异常
    • commitAndClose() 提交事务并释放连接
  3. ResultSetHandler接口,主要用于封装结果集
    • 9个实现类——ArrayHandler, ArrayListHandler, BeanHandler, BeanListHandler, ColumnListHandler, KeyedHandler, MapHandler, MapListHandler, ScalarHandler
    • ArrayHandler, 将查询结果的第一条记录封装成数组,返回
    • ArrayListHandler, 将查询结果的每一条记录封装成数组,将每一个数组放入list中返回
    • ★★BeanHandler, 将查询结果的第一条记录封装成指定的bean对象,返回
    • ★★BeanListHandler,将查询结果的每一条记录封装成指定的bean对象,将每一个bean对象放入list中 返回.
    • ColumnListHandler, 将查询结果的指定一列放入list中返回
    • MapHandler, 将查询结果的第一条记录封装成map,字段名作为key,值为value 返回
    • ★MapListHandler, 将查询结果的每一条记录封装map集合,将每一个map集合放入list中返回
    • ★ScalarHandler,针对于聚合函数 例如:count(*) 返回的是一个Long值
    • 使用方式几乎都一样,这里以 ArrayHandler 举例
    QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());
    String sql = "insert into category(cid,cname) values(?,?)";
    object[] query = queryRunner.query(sql,new ArrayHandler());
    • 特别介绍下 bean
    QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());
    String sql = "insert into category(cid,cname) values(?,?)";
    // bean.class 表示 声明的 bean,其字段和数据库字段对应
    object[] query = queryRunner.query(sql,new BeanHandler<>(bean.class));
    欢迎大家关注我的个人公众号,互联网码农,专注互联网编程技术分享,关注公众号,回复关键字,可以领取系列编程学习视频哦,前端、java、ios、安卓、c++、python应用尽有。

猜你喜欢

转载自www.cnblogs.com/blogcxz/p/11198135.html