JAVA数据库技术

一、        JDBC数据库操作

1.     JDBC连接数据库步骤

1)   加载数据库驱动

Class.forName(“com.mysql.jdbc.Driver”);

2)   获取连接

Connection conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/fpga?useUnicode=true&characterEncoding=UTF-8”, username, password);

3)   获取Statement

PreparedStatement ps = conn.prepareStatement(sql);

4)   执行sql(获取结果集)

ResultSet rs = rs = ps.executeQuery();

5)   对结果集进行操作

if (rs.next())

{

}

6)   关闭连接

rs.close();

ps.close();

conn.close();

 

2.     使用JDBC进行增删查改操作

3.     元数据介绍

4.     事务

二、        数据库连接池技术

1.     DBCP连接池

  1. 代码实现

package com.zte.kms.util;

import java.io.InputStream;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Properties;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public final class DBUtil

{

    //定义数据源静态变量,采用单例模式

    private static DataSource myDataSource = null;

    //私有的构造方法,不允许构造DBUtil实例

    private DBUtil()

    {

    }

    //静态代码块,初始化连接池,只是系统加载的时候初始化一次(单例)

    static

    {

        try

        {

                     //定义属性配置信息

            Properties prop = new Properties();

            //加载配置文件为输入流

InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");

//把输入流的配置文件加载到属性文件中

            prop.load(is);

            //利用属性文件的配置信息初始化数据源

            myDataSource = BasicDataSourceFactory.createDataSource(prop);

        }

        catch (Exception e)

        {

            e.printStackTrace();

        }

    }

    /**

     * 从连接池中获取一个连接。

     * @return  获取到的连接。

     * @throws  SQLException

     */

    public static Connection getConnection() throws SQLException

    {

        return myDataSource.getConnection();

    }

    /**

     * 获取当前正在使用的DBCP数据源信息。

     * @return  DBCP数据源

     */

    public static DataSource getDataSource()

    {

        return myDataSource;

    }

    /**

     * 把连接放回到连接池中。

     * @param  conn 数据库连接

     * @param  ps   执行的预处理SQL语句

     * @param rs   结果集

     */

    public static void free(Connection conn, PreparedStatement ps, ResultSet rs)

    {

        //1.先关闭结果集。

        if (null != rs)

        {

            try

            {

                rs.close();

            }

            catch (SQLException ex)

            {

                Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);

            }

        }

        //2.关闭preparedstatement

        if (null != ps)

        {

            try

            {

                ps.close();

            }

            catch (SQLException ex)

            {

                Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);

            }

        }

        //3.关闭连接放到连接池中

        if (null != conn)

        {

            try

            {

                //3.关闭连接放到连接池中

                conn.close();

            }

            catch (SQLException ex)

            {

                Logger.getLogger(DBUtil.class.getName()).log(Level.SEVERE, null, ex);

            }

        }

}

}

  1. 配置文件(dbcpconfig.properties放在classpath目录下)

#####################################################

###数据库配置相关信息,此文件是整个系统中最重要的文件,

####注意:此处的用户名,密码在正式使用时需要修改。

#####################################################

 

#连接设置

driverClassName=com.mysql.jdbc.Driver

url=jdbc:mysql://10.94.119.14:3306/kms?useUnicode=true&characterEncoding=UTF-8

username=root

password=root

 

#<!-- 初始化连接 -->

dataSource.initialSize=30

 

#<!-- 最大空闲连接 -->

dataSource.maxIdle=10

 

#<!-- 最小空闲连接 -->

dataSource.minIdle=5

 

#最大连接数量

dataSource.maxActive=50

 

#是否在自动回收超时连接的时候打印连接的超时错误

dataSource.logAbandoned=true

 

#是否自动回收超时连接

dataSource.removeAbandoned=true

 

#超时时间(以秒数为单位)

#设置超时时间有一个要注意的地方,超时时间=现在的时间-程序中创建Connection的时间,如果 maxActive比较大,比如超过100,那么removeAbandonedTimeout可以设置长一点比如180,也就是三分钟无响应的连接进行回收,当然应用的不同设置长度也不同。

dataSource.removeAbandonedTimeout=180

 

#<!-- 超时等待时间以毫秒为单位 -->

#maxWait代表当Connection用尽了,多久之后进行回收丢失连接

dataSource.maxWait=2000

2.     C3P0

1) 代码实现

/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

package com.zte.jdbc;

 

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.sql.DataSource;

 

/**

 * 数据库连接池,C3P0实现。

 * @author WuBaoGui

 */

public class C3P0Util

{

    //私有静态变量,只是系统初始化加载一次,单例模式

    private static ComboPooledDataSource ds = new ComboPooledDataSource();

 

    /**

     * C3P0连接池获取一个数据库连接。

     * @return

     */

    public static Connection getConnection()

    {

        Connection connection = null;

        try

        {

            connection = ds.getConnection();

        }

        catch (SQLException ex)

        {

            Logger.getLogger(C3P0Util.class.getName()).log(Level.SEVERE, null, ex);

        }

 

        return connection;

    }

 

    public static DataSource getDataSource()

    {

        return ds;

    }

 

    /**

     * 释放资源

     *

     * @param conn 释放Connection

     * @param ps 释放Statement

     * @param rs 释放ResultSet

     */

    public static void release(Connection conn, Statement ps, ResultSet rs)

    {

        if (rs != null)

        {

            try

            {

                rs.close();

            }

            catch (SQLException e)

            {

                throw new RuntimeException(e);

            }

            finally

            {

                rs = null;

            }

        }

        if (ps != null)

        {

            try

            {

                ps.close();

            }

            catch (SQLException e)

            {

                throw new RuntimeException(e);

            }

            finally

            {

                ps = null;

            }

        }

        if (conn != null)

        {

            try

            {

                conn.close();

            }

            catch (SQLException e)

            {

                throw new RuntimeException(e);

            }

            finally

            {

                conn = null;

            }

        }

    }

}

2) 配置文件(c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<c3p0-config>

    <default-config>

        <property name="driverClass">com.mysql.jdbc.Driver</property>

        <property name="jdbcUrl">jdbc:mysql://localhost:3306/kms</property>

        <property name="user">root</property>

        <property name="password">123456</property>

        <property name="acquireIncrement">5</property>

        <property name="initialPoolSize">20</property>

        <property name="minPoolSize">10</property>

        <property name="maxPoolSize">50</property>

    </default-config>

 

    <named-config name="oracle">

        <property name="driverClass">oracle.jdbc.OracleDriver</property>

        <property name="jdbcUrl">jdbc:oracle:thin:@localhost:1521:orcl</property>

        <property name="user">scott</property>

        <property name="password">tiger</property>

        <property name="acquireIncrement">50</property>

        <property name="initialPoolSize">100</property>

        <property name="minPoolSize">50</property>

        <property name="maxPoolSize">1000</property>

    </named-config>

</c3p0-config>

三、        DBUtils使用

1.     主要类介绍

DBUtilsJDBC进行了二次封装,可以把结果集转换为对象或List,对于数据库的表的写操作,也只需要sql即可。可以使用数据源,JNDI,数据库连接池等技术对性能进行优化。主要类如下:

  • DbUtils 关闭链接等操作

  • QueryRunner 进行查询的操作

  • ArrayHandler :将ResultSet中第一行的数据转化成对象数组

  • ArrayListHandlerResultSet中所有的数据转化成ListList中存放的是Object[]

  • BeanHandler :将ResultSet中第一行的数据转化成类对象

  • BeanListHandler :将ResultSet中所有的数据转化成ListList中存放的是类对象

  • ColumnListHandler :将ResultSet中某一列的数据存成ListList中存放的是Object对象

  • KeyedHandler :将ResultSet中存成映射,key为某一列对应为MapMap中存放的是数据

  • MapHandler :将ResultSet中第一行的数据存成Map映射

  • MapListHandler :将ResultSet中所有的数据存成ListList中存放的是Map

  • ScalarHandler :将ResultSet中一条记录的其中某一列的数据存成Object

  • SqlNullCheckedResultSet :对ResultSet进行操作,改版里面的值

  • StringTrimmedResultSet :去除ResultSet中中字段的左右空格。Trim()

090151_nQQz_565171.png

2.     和数据库连接池实现CRUD操作

1)   增加

public void testAdd()

    {

        String sql = "insert into tbl_role (name, flag) values (?, ?)";

        QueryRunner qRunner = new QueryRunner(C3P0Util.getDataSource());

        try

        {

            int result = qRunner.update(sql, "QQQ", 1);

        }

        catch (SQLException ex)

        {

            Logger.getLogger(C3P0UtilTest.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

2)   修改

public void testMod()

{

        String sql = "update tbl_role set name = ? where id = ?";

        QueryRunner qRunner = new QueryRunner(C3P0Util.getDataSource());

        try

        {

            int result = qRunner.update(sql, "ZZZ", 9);

        }

        catch (SQLException ex)

        {

            Logger.getLogger(C3P0UtilTest.class.getName()).log(Level.SEVERE, null, ex);

        }

}

3)   删除

public void testDel()

{

        String sql = "delete from tbl_role where id = ?";

        QueryRunner qRunner = new QueryRunner(C3P0Util.getDataSource());

        try

        {

            int result = qRunner.update(sql, 9);

            System.out.print(result);

        }

        catch (SQLException ex)

        {

            Logger.getLogger(C3P0UtilTest.class.getName()).log(Level.SEVERE, null, ex);

        }

}

4)   查询

public void testGet()

    {

        String sql = "select * from tbl_role where id = ?";

        QueryRunner qRunner = new QueryRunner(C3P0Util.getDataSource());

        BeanHandler rsh = new BeanHandler(Role.class);

        try

        {

            Role role = (Role) qRunner.query(sql, rsh, 10);

            System.out.println(role.getName());

        }

        catch (SQLException ex)

        {

            Logger.getLogger(C3P0UtilTest.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

public void testList()

    {

        String sql = "select * from tbl_role";

        QueryRunner qRunner = new QueryRunner(C3P0Util.getDataSource());

        try

        {

            List<Role> roles = qRunner.query(sql, new BeanListHandler<Role>(Role.class), 2);

        }

        catch (SQLException ex)

        {

            Logger.getLogger(C3P0UtilTest.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

5)   BlobClob对象的存储

//使用dbutils实现大文本对象的存储.
  
 @Test
    public void testClob() throws Exception{
        String sql="insert into article (content)values(?)";
        File file=new File("bin/stylesheet.css");
        char[] c=new char[(int)file.length()];
        FileReader reader=new FileReader(file);
        reader.read(c);
        SerialClob clob=new SerialClob(c);
        QueryRunner runner=new QueryRunner(JDBCUtils.getDataSource());
        runner.update(sql, clob);
    }
    //
使用dbutils实现二进制对象的存储.
    @Test
    public void testBlob() throws Exception{
        String sql="insert into image (content)values(?)";
        File file=new File("bin/bg.jpg");
        byte[] b=new byte[(int)file.length()];
        InputStream in=new FileInputStream(file);
        in.read(b);
        SerialBlob blob=new SerialBlob(b);
        QueryRunner runner=new QueryRunner(JDBCUtils.getDataSource());
        runner.update(sql,blob);
    }

6)   批处理操作

@Test

public void testBatch() throws SQLException

{

        String sql = "insert into tbl_role (name, flag) values (?, ?)";

        Object[][] params = new Object[10][];

        QueryRunner qRunner = new QueryRunner(C3P0Util.getDataSource());

        for (int i = 0; i < 10; i++)

        {

            params[i] = new Object[]

            {

                "batch" + i, i

            };

        }

        qRunner.batch(sql, params);

    }

7)   事务处理

090249_i14w_565171.png

090329_pOxF_565171.png

 

四、        MyBatis使用

1.     MyBatis使用步骤

2.     配置文件

3.     增删查改

4.     复杂查询

五、        Hibernate使用


转载于:https://my.oschina.net/looten/blog/306574

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值