Jdbc及ibatis连库实例

​​​

目录

1.Jdbc连接Mysql实现增删改查

2.Mysql通用分页:

3.Jdbc连接Oracle数据库

4.Oracle通用分页:

5.DBUtils使用

6.ibatis-连库实例

1.resources 文件夹下新建SqlMap.xml

2.新建SqlMapConfig.properties

3.新建SqlMapConfig.xml

4.测试


​​​​​​​

  • 没有Mybatis的时候都是用的Jdbc,Mybatis实际就是对Jdbc做的封装
  • JDBC(Java DataBase Connectivity)是 Java 程序与关系型数据库交互的统一 API。实际上,JDBC 由两部分 API 构成:第一部分是面向 Java 开发者的 Java API,它是一个统一的、标准的 Java API,独立于各个数据库产品的接口规范;第二部分是面向数据库驱动程序开发者的 API,它是由各个数据库厂家提供的数据库驱动,是第一部分接口规范的底层实现,用于连接具体的数据库产品。

1.Jdbc连接Mysql实现增删改查

public class JdbcUtil {

    //定义MySQL的数据库驱动程序
    public static final String MYSQL_DBDRIVER = "com.mysql.jdbc.Driver";
    //定义Oracle的数据库驱动程序
    public static final String ORACLE_DBDRIVER = "oracle.jdbc.driver.OracleDriver";
    //定义MySQL数据库的连接地址
    public static final String DBURL = "jdbc:mysql://localhost:3306/test";
    //MySQL数据库的连接用户名
    public static final String DBUSER = "root";
    //MySQL数据库的连接密码
    public static final String DBPASS = "";

    static {
        try {
            // 加载驱动
            Class.forName(MYSQL_DBDRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Author faYi
     * @Description  获得连接
     * @Date  2020/4/11 21:37
     * @Param []
     * @return java.sql.Connection
     **/
    public static Connection getCon() throws SQLException {
        Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
        return conn;
    }
    
    /**
     * @Author faYi
     * @Description  释放资源conn,st,rs
     * @Date  2020/4/11 23:35
     * @Param [conn, st, rs]
     * @return void
     **/
    public static void close(Connection conn, Statement st, ResultSet rs){
        try {
            if(rs != null){
                rs.close();
            }
            closeConnAndSt(conn,st);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * @Author faYi
     * @Description  释放资源conn,st
     * @Date  2020/4/11 23:54
     * @Param [conn, st]
     * @return void
     **/
    public static void closeConnAndSt(Connection conn, Statement st){
        try {
            if(st != null){
                st.close();
            }
            if(conn != null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }



}


public static void main(String[] args) {
        try {
            Connection con = JdbcUtil.getCon();
            //3.创建statement
            Statement st = con.createStatement();
            //4.执行插入
            String sql = "insert into sys_user values(null, 'SB', 250)";
            int count = st.executeUpdate(sql);
            if (count > 0){
                System.out.println("添加成功");
            }else {
                System.out.println("添加失败");
            }
            JdbcUtil.closeConnAndSt(con,st);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


public static void main(String[] args) {
        try {
            Connection con = JdbcUtil.getCon();
            //3.创建statement
            Statement st = con.createStatement();
            //4.执行更新
            String sql = "update sys_user set telephone = '110' where username = 'SB'";
            int count = st.executeUpdate(sql);
            if (count > 0){
                System.out.println("更新成功");
            }else {
                System.out.println("更新失败");
            }
            JdbcUtil.closeConnAndSt(con,st);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


public static void main(String[] args) {
        try {
            Connection con = JdbcUtil.getCon();
            //3.创建statement
            Statement st = con.createStatement();
            //4.执行删除
            String sql = "delete from sys_user where username = 'SB'";
            int count = st.executeUpdate(sql);
            if (count > 0){
                System.out.println("删除成功");
            }else {
                System.out.println("删除失败");
            }
            JdbcUtil.closeConnAndSt(con,st);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.Mysql通用分页:

import java.util.List;

/**
 * @Author faYi
 * @Date 2020/4/12 13:27
 * @Description
 */
public class MysqlPageUntil<T> {
    /**
     * 起始索引
     */
    private int startIndex;
    /**
     * currentPage 当前页
     */
    private int currentPage ;
    /**
     * pageSize 每页大小
     */
    private int pageSize ;
    /**
     * pageTotal 总页数
     */
    private int pageTotal;
    /**
     * recordTotal 总条数
     */
    private int recordTotal ;

    /**
     * content 每页的内容
     */
    private List<T> list;

    public MysqlPageUntil(){

    }

    public MysqlPageUntil(int pageNum,int pageSize,int totalCount){
        this.pageSize = pageSize;
        if (totalCount < pageSize){
            this.pageTotal = 1;
        }
        this.pageTotal = totalCount % pageSize ==0 ? totalCount/pageSize :(totalCount/pageSize)+1;
        this.currentPage = pageNum < 1 ? 1 : pageNum;
        this.currentPage = pageNum > this.pageTotal ? this.pageTotal : this.currentPage;
        // 从(pageNum-1) * pageSize 开始取数据,取lineSize条数据
        startIndex = (pageNum-1)*pageSize;
        this.recordTotal = totalCount;
    }

    public int getStartIndex() {
        return startIndex;
    }

    public void setStartIndex(int startIndex) {
        this.startIndex = startIndex;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getPageTotal() {
        return pageTotal;
    }

    public void setPageTotal(int pageTotal) {
        this.pageTotal = pageTotal;
    }

    public int getRecordTotal() {
        return recordTotal;
    }

    public void setRecordTotal(int recordTotal) {
        this.recordTotal = recordTotal;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    @Override
    public String toString() {
        return "MysqlPageUntil{" +
                "startIndex=" + startIndex +
                ", currentPage=" + currentPage +
                ", pageSize=" + pageSize +
                ", pageTotal=" + pageTotal +
                ", recordTotal=" + recordTotal +
                ", list=" + list +
                '}';
    }
}





 @Test
    public void testPageDataBeanListHandler() throws Exception {
        int pageNum = 1; // 当前页数
        int pageSize = 10;// 每页显示数据的数量
        QueryRunner queryRunner = new QueryRunner();
        String countSql = "SELECT count(*)  FROM sys_user";
        // ScalarHandler 查询后,只有1个结果
        long totalCount = queryRunner.query(JdbcUtil.getCon(), countSql, new ScalarHandler<>());
        MysqlPageUntil mysqlPageUntil = new MysqlPageUntil(pageNum,pageSize, (int) totalCount);
        String sql = "SELECT username,telephone  FROM sys_user LIMIT ?,?";
        // 查询分页
        List<SysUser> userList = (List<SysUser>)queryRunner.query(JdbcUtil.getCon(), sql, new BeanListHandler(SysUser.class), new Object[]{mysqlPageUntil.getStartIndex(), pageSize});
        mysqlPageUntil.setList(userList);
        System.out.println(mysqlPageUntil);
    }

3.Jdbc连接Oracle数据库

public class Test {
    //Oracle数据库的连接地址
    public static final String DBURL = "jdbc:oracle:thin:@127.0.0.1:1521:ORCL";
    //Oracle数据库的连接用户名
    public static final String DBUSER = "sysman";
    //Oracle数据库的连接密码
    public static final String DBPASS = "root";
    public static void main(String[] args) {
        try {
            //1.加载驱动
            Class.forName("oracle.jdbc.driver.OracleDriver");
            //2.建立连接
            Connection conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
            //3.创建statement
            Statement st = conn.createStatement();
            String sql = "select * from SYSMAN.sys_user";
            //4.执行sql
            ResultSet rs = st.executeQuery(sql);
            while (rs.next()){
                // 遍历结果集
                System.out.println(rs.getInt("ID"));
                System.out.println(rs.getString("USERNAME"));
                System.out.println(rs.getString("TELEPHONE"));
            }
            // 释放资源
            conn.close();
            st.close();
            rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4.Oracle通用分页:

public class OraclePageUntil<T> {
    /**
     * 起始索引
     */
    private int startIndex;
    /**
     * currentPage 当前页
     */
    private int currentPage;
    /**
     * pageSize 每页大小
     */
    private int pageSize;
    /**
     * pageTotal 总页数
     */
    private int pageTotal;
    /**
     * recordTotal 总条数
     */
    private int recordTotal;
 
    /**
     * content 每页的内容
     */
    private List<T> list;
 
    /**
     * content 读取前N条数据
     */
    private int readTotal;
 
 
    public OraclePageUntil(int pageNum, int pageSize, int totalCount) {
        this.pageSize = pageSize;
        if (totalCount < pageSize) {
            this.pageTotal = 1;
        }
        this.pageTotal = totalCount % pageSize == 0 ? totalCount / pageSize : (totalCount / pageSize) + 1;
        this.currentPage = pageNum < 1 ? 1 : pageNum;
        this.currentPage = pageNum > this.pageTotal ? this.pageTotal : this.currentPage;
        // 从(pageNum-1) * pageSize 开始取数据,取lineSize条数据
        startIndex = (pageNum - 1) * pageSize;
        this.recordTotal = totalCount;
        this.readTotal = pageNum * pageSize;
    }
 
    public int getStartIndex() {
        return startIndex;
    }
 
    public void setStartIndex(int startIndex) {
        this.startIndex = startIndex;
    }
 
    public int getCurrentPage() {
        return currentPage;
    }
 
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }
 
    public int getPageSize() {
        return pageSize;
    }
 
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
 
    public int getPageTotal() {
        return pageTotal;
    }
 
    public void setPageTotal(int pageTotal) {
        this.pageTotal = pageTotal;
    }
 
    public int getRecordTotal() {
        return recordTotal;
    }
 
    public void setRecordTotal(int recordTotal) {
        this.recordTotal = recordTotal;
    }
 
    public List<T> getList() {
        return list;
    }
 
    public void setList(List<T> list) {
        this.list = list;
    }
 
    public int getReadTotal() {
        return readTotal;
    }
 
    public void setReadTotal(int readTotal) {
        this.readTotal = readTotal;
    }
 
    @Override
    public String toString() {
        return "OraclePageUntil{" +
                "startIndex=" + startIndex +
                ", currentPage=" + currentPage +
                ", pageSize=" + pageSize +
                ", pageTotal=" + pageTotal +
                ", recordTotal=" + recordTotal +
                ", list=" + list +
                ", readTotal=" + readTotal +
                '}';
    }
}

测试:

public class TestOraclePage {
 
    /*
     Oracle分页:
       Oracle的分页依赖于ROWNUM这个伪列,ROWNUM主要作用就是产生行号。
     分页原理:
       1:子查询查出前n行数据,ROWNUM产生前N行的行号
       2:使用子查询产生ROWNUM的行号,通过外部的筛选出想要的数据
     例子:
       我现在规定每页显示2行数据【pageSize=2】,我要查询第3页的数据【pageSize=3】
       注:【对照着sql语法来看】
     实现:
       1:子查询查出前6条数据【ROWNUM<=6】
       2:外部筛选出后面4条数据【ROWNUM>4】
       3:这样我们就取到了第5条和第六条数据
   */
    @Test
    public void testOraclePage() throws Exception {
        int pageNum = 3; // 当前页数
        int pageSize = 2;// 每页显示数据的数量
        QueryRunner queryRunner = new QueryRunner();
        String countSql = "SELECT count(*)  FROM sys_user";
        // ScalarHandler 查询后,只有1个结果
        BigDecimal totalCount = queryRunner.query(JdbcUtil.getCon(), countSql, new ScalarHandler<>());
        OraclePageUntil pageUntil = new OraclePageUntil(pageNum, pageSize, totalCount.intValue());
        String sql = "SELECT * FROM" +
                     "(SELECT t.*,ROWNUM r FROM SYSMAN.sys_user t WHERE ROWNUM <= ?)" +
                     " WHERE r > ?";
        // 查询分页数据
        List<SysUser> userList = (List<SysUser>) queryRunner.query(JdbcUtil.getCon(), sql, new BeanListHandler(SysUser.class), new Object[]{pageUntil.getReadTotal(), pageUntil.getStartIndex()});
        pageUntil.setList(userList);
        System.out.println(pageUntil);
    }
 
}

5.DBUtils使用

 commons-dbutils : Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,QueryRunner类与ResultSetHandler组合在一起使用可以完成大部分的数据库操作,极大简化jdbc编码的工作量

<dependency>
      <groupId>commons-dbutils</groupId>
      <artifactId>commons-dbutils</artifactId>
      <version>1.7</version>
</dependency>

public class TestDBUntils {
 
    // BeanListHandler 将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里
    @Test
    public void testBeanListHandler() throws Exception {
        String sql = "SELECT username,telephone  FROM sys_user";
        //从哪个位置开始取数据
        QueryRunner queryRunner = new QueryRunner();
        List<SysUser> userList = (List<SysUser>) queryRunner.query(JdbcUtil.getCon(), sql, new BeanListHandler(SysUser.class));
        System.out.println(userList);
    }
 
    //ArrayHandler 将查询结果的第一行数据,保存到Object数组中
    @Test
    public void testArrayHandler() throws SQLException {
        String sql = "SELECT *  FROM sys_user";
        QueryRunner queryRunner = new QueryRunner();
        Object[] res = null;
        res = queryRunner.query(JdbcUtil.getCon(), sql, new ArrayHandler(), new Object[]{});
        System.out.println(Arrays.toString(res)); // [1, Admin, 18612344321]
    }
 
    //BeanHandler 将结果集中的第一行数据封装到一个对应的JavaBean实例中
    @Test
    public void testBeanHandler() throws Exception {
        String sql = "SELECT *  FROM sys_user";
        QueryRunner queryRunner = new QueryRunner();
        SysUser sysUser = (SysUser) queryRunner.query(JdbcUtil.getCon(), sql, new BeanHandler(SysUser.class));
        System.out.println(sysUser); // sysUser{id=1, username='Admin', telephone='18612344321'}
    }
 
    //ArrayListHandler 把结果集中的每一行数据都转成一个数组,再存放到List中。
    @Test
    public void testArrayListHandler() throws Exception {
        String sql = "SELECT *  FROM sys_user";
        QueryRunner queryRunner = new QueryRunner();
        List<Object[]> res = queryRunner.query(JdbcUtil.getCon(), sql, new ArrayListHandler());
        for (Object[] re : res) {
            System.out.print(Arrays.toString(re));//[1, Admin, 18612344321][2, Jimin, 13188889999][3, Jimmy, 13812344311]
        }
    }
 
    //ColumnListHandler 将结果集中某一列的数据存放到List中
    @Test
    public void testColumnListHandler() throws Exception {
        String sql = "SELECT *  FROM sys_user";
        QueryRunner queryRunner = new QueryRunner();
        List res = (List) queryRunner.query(JdbcUtil.getCon(), sql, new ColumnListHandler("username"));
        System.out.print(res.toString());//[Admin, Jimin, Jimmy]
    }
 
    //KeyedHandler:将结果集中的每一行数据都封装到一个Map里,再把这些map再存到一个map里,其key为指定的key。
    @Test
    public void testKeyedHandler() throws Exception {
        String sql = "SELECT *  FROM sys_user";
        QueryRunner queryRunner = new QueryRunner();
        Object object = queryRunner.query(JdbcUtil.getCon(), sql, new KeyedHandler("id"));
        System.out.println(object); // {1={id=1, username=Admin, telephone=18612344321}, 2={id=2, username=Jimin, telephone=13188889999}, 3={id=3, username=Jimmy, telephone=13812344311}}
        Map<Integer, Map> resMap = (Map<Integer, Map>) queryRunner.query(JdbcUtil.getCon(), sql, new KeyedHandler("id"));
        for (Map.Entry<Integer, Map> entry : resMap.entrySet()) {
            Map<String, Object> innerMap = entry.getValue();
            for (Map.Entry<String, Object> innerEntry : innerMap.entrySet()) {
                System.out.println(innerEntry.getKey() + "=" + innerEntry.getValue());
            }
        }
    }
 
    // MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
    @Test
    public void testMapHandler() throws Exception {
        String sql = "SELECT *  FROM sys_user";
        QueryRunner queryRunner = new QueryRunner();
        Map<String, Object> resMap = queryRunner.query(JdbcUtil.getCon(), sql, new MapHandler());
        System.out.println(resMap);// {id=1, username=Admin, telephone=18612344321}
    }
 
    // MapListHandler 将结果集中的每一行数据都封装到一个Map里,然后再存放到List
    @Test
    public void testMapListHandler() throws Exception {
        String sql = "SELECT *  FROM sys_user";
        QueryRunner queryRunner = new QueryRunner();
        List<Map<String, Object>> resMap = queryRunner.query(JdbcUtil.getCon(), sql, new MapListHandler());
        System.out.println(resMap);// [{id=1, username=Admin, telephone=18612344321}, {id=2, username=Jimin, telephone=13188889999}, {id=3, username=Jimmy, telephone=13812344311}]
        for (Map<String, Object> map : resMap) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                System.out.println(entry.getKey() + "=" + entry.getValue());
            }
        }
    }
 
}

6.ibatis-连库实例

mybaits的前身是ibatis,很多需要维护的老项目还在用,之前有碰到过

1.resources 文件夹下新建SqlMap.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
        "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap>
    <select id="getAllUsers" parameterClass="string" resultClass="user">
        SELECT id,username,telephone
        FROM sys_user
        WHERE id = #id#
    </select>

</sqlMap>

2.新建SqlMapConfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=

3.新建SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
        "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
    <properties resource="SqlMapConfig.properties" />
    <typeAlias alias="user" type="pojo.SysUser" />

    <transactionManager type="JDBC">
        <dataSource type="SIMPLE">
            <property name="JDBC.Driver" value="${jdbc.driver}" />
            <property name="JDBC.ConnectionURL" value="${jdbc.url}" />
            <property name="JDBC.Username" value="${jdbc.username}" />
            <property name="JDBC.Password" value="${jdbc.password}" />
        </dataSource>
    </transactionManager>
    <sqlMap resource="SqlMap.xml" />
</sqlMapConfig>

4.测试

public class SysUser {
    private Integer id;
    private String username;
    private String telephone;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    @Override
    public String toString() {
        return "sysUser{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", telephone='" + telephone + '\'' +
                '}';
    }
}
public class TestIBatis {
    //使用sqlMapClient,此类线程安全,所以可以定义成静态的
    private static SqlMapClient sqlMaper;
    //静态块,初始化 sqlMaper;在类加载的时候执行一次
    static {
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader("SqlMapConfig.xml");
            sqlMaper = SqlMapClientBuilder.buildSqlMapClient(reader);
            reader.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String str[]) throws Exception {
        List<SysUser> list = sqlMaper.queryForList("getAllUsers", "1");
        System.out.println(list);
        //[sysUser{id=1, username='Admin', telephone='18612344321'}]
    }

}

这是一个用iBator生成iBatis有关代码的例子。 特别说明: Eclipse应该是3.4.1以上版本, 并且安装了iBator插件。否则可用iBator的命令行版本或ant工具。 测试用数据是: CREATE TABLE PERSON( id INTEGER NOT NULL, firstName VARCHAR (40) NOT NULL, lastName VARCHAR (40) NOT NULL, PRIMARY KEY (ID) ); insert into PERSON values (1,'ng','Huang'); insert into PERSON values (2,'zh','Ni'); insert into PERSON values (3,'zy','Huang'); src下有三个目录: ibator/config:配置文件,其中: ibatorConfig.xml:iBaotr的配置文件,指示iBator如何生成代码,其中classPathEntry要指向一个 jdbc 驱动程序。 sqlMapConfig.properties:数据库配置,配置数据库密码等 AppSqlConfig.java:应用程序配置,如果目录结构相同,不必修改 SqlMapConfig.xml:SqlMap配置,在最后应该加上每个表的Map文件,特别注意useStatementNamespaces="true"不能为false org:生成的代码,分为三个目录,目录名在ibatorConfig.xml中指定 注意:其中生成的person_SqlMap.xml中的: <select id="ibatorgenerated_selectByPrimaryKey" resultMap="ibatorgenerated_BaseResultMap" > 经过修改了, 删除了parameterClass="org....的内容 test:一个测试主程序。运行它能得到数据库中的数据。 如何使用这个例子: 1、下载后解压缩 2、导入到Eclipse中 3、运行test/Test.java,看看结果 4、删除org及其下的三个目录及文件 5、在ibator/config/ibatorConfig.xml中的右键菜单,选择Generate iBATIS Artifacts 5、将自动生成org中的所有代码,研究一下这些代码 6、修改中的person_SqlMap.xml中的: <select id="ibatorgenerated_selectByPrimaryKey" resultMap="ibatorgenerated_BaseResultMap" > 7、再次执行test/Test.java,看看结果 8、研究ibator/config中的各个文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值