• 原生的数据库访问和操作


    基于sql相关jar包的原生的数据库访问和操作,sql server、mysql以及oracle只有链接数据的参数不一样,方法一样,以mysql为例,先封装一个简单的类,用于打开和关闭数据连接:

    package com.wmqiangproject.util;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public class DBUtil {
        /**
         * 连接数据库的操作,用户名,密码,使用jdbc连接
         */
        public static String username = "root";
        public static String password = "root";
        public static String url = "jdbc:mysql://localhost:3306/wmqiangproject";
        
        static{
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch(ClassNotFoundException e){
                e.printStackTrace();
            }
        }
        
        public static Connection getConnectDb(){
            Connection conn = null;
            try{
                conn = DriverManager.getConnection(url,username,password);
            
            } catch (SQLException e){
                e.printStackTrace();
            }
            return conn;
        }
        
        public static void CloseDB(ResultSet rs, PreparedStatement stm, Connection conn){
            if(rs!=null)
            {
                try {
                    rs.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(stm!=null)
            {
                try {
                    stm.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(conn!=null)
            {
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    代码中访问数据库增删改查,以一个图书管理系统Dao层数据库访问层代码为例:

        
    package com.wmqiangproject.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Calendar;
    
    import com.wmqiangproject.bean.AdminBean;
    import com.wmqiangproject.bean.BookBean;
    import com.wmqiangproject.bean.HistoryBean;
    import com.wmqiangproject.bean.TypeBean;
    import com.wmqiangproject.util.DBUtil;
    /**
     * 关于图书连接数据库的所有操作的类
     */
    public class BookDao {
    
        /**
         * 添加图书信息,传入所有的信息
         * @param card
         * @param name
         * @param type
         * @param autho
         * @param press
         * @param num
         */
        public void addBook(String card, String name, String type, String autho, String press, int num) {
            // TODO Auto-generated method stub
            Connection conn = DBUtil.getConnectDb();
            String sql = "insert  into book(card,name,type,autho,press,num) values(?,?,?,?,?,?)";
            int rs = 0;
            PreparedStatement stm = null;
            try {
                stm = conn.prepareStatement(sql);
                stm.setString(1, card);
                stm.setString(2, name);
                stm.setString(3, type);
                stm.setString(4, autho);
                stm.setString(5, press);
                stm.setInt(6, num);
                rs = stm.executeUpdate();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        /**
         * 获取所有的图书信息,返回的是ArrayList数组形式
         * @return
         */
        public ArrayList<BookBean> get_ListInfo(){
            ArrayList<BookBean> tag_Array = new ArrayList<BookBean>();
            Connection conn = DBUtil.getConnectDb();
            String sql = "select * from book";
            PreparedStatement stm = null;
            ResultSet rs = null;
            try {
                stm = conn.prepareStatement(sql);
                rs = stm.executeQuery();
                while(rs.next()){
                    BookBean tag = new BookBean();
                    tag.setBid(rs.getInt("bid"));
                    tag.setName(rs.getString("name"));
                    tag.setCard(rs.getString("card"));
                    tag.setType(rs.getString("type"));
                    tag.setAutho(rs.getString("autho"));
                    tag.setPress(rs.getString("press"));
                    tag.setNum(rs.getInt("num"));
                    tag_Array.add(tag);
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                DBUtil.CloseDB(rs, stm, conn);
            }
            return tag_Array;
        }
        /**
         * 获取借阅记录的全部信息,传入的条件有status,aid,表示搜索正在借阅的,或者已经还书的信息,aid代表当前登录用户
         * @param status
         * @return
         */
        public ArrayList<HistoryBean> get_HistoryListInfo(int status,String aid){
            ArrayList<HistoryBean> tag_Array = new ArrayList<HistoryBean>();
            Connection conn = DBUtil.getConnectDb();
            String sql = "select * from history where aid="+aid+" and status="+status;
            PreparedStatement stm = null;
            ResultSet rs = null;
            try {
                stm = conn.prepareStatement(sql);
                rs = stm.executeQuery();
                while(rs.next()){
                    HistoryBean tag = new HistoryBean();
                    tag.setHid(rs.getInt("hid"));
                    tag.setAid(rs.getInt("aid"));
                    tag.setBid(rs.getInt("bid"));
                    tag.setBookname(rs.getString("bookname"));
                    tag.setCard(rs.getString("card"));
                    tag.setAdminname(rs.getString("adminname"));
                    tag.setUsername(rs.getString("username"));
                    tag.setBegintime(rs.getString("begintime"));
                    tag.setEndtime(rs.getString("endtime"));
                    tag.setStatus(rs.getInt("status"));
                    tag_Array.add(tag);
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                DBUtil.CloseDB(rs, stm, conn);
            }
            return tag_Array;
        }
        /**
         * 获取借阅记录的全部信息,传入的条件有status,表示搜索正在借阅的,或者已经还书的信息
         * @param status
         * @return
         */
        public ArrayList<HistoryBean> get_HistoryListInfo2(int status){
            ArrayList<HistoryBean> tag_Array = new ArrayList<HistoryBean>();
            Connection conn = DBUtil.getConnectDb();
            String sql = "select * from history where status="+status;
            PreparedStatement stm = null;
            ResultSet rs = null;
            try {
                stm = conn.prepareStatement(sql);
                rs = stm.executeQuery();
                while(rs.next()){
                    HistoryBean tag = new HistoryBean();
                    tag.setHid(rs.getInt("hid"));
                    tag.setAid(rs.getInt("aid"));
                    tag.setBid(rs.getInt("bid"));
                    tag.setBookname(rs.getString("bookname"));
                    tag.setCard(rs.getString("card"));
                    tag.setAdminname(rs.getString("adminname"));
                    tag.setUsername(rs.getString("username"));
                    tag.setBegintime(rs.getString("begintime"));
                    tag.setEndtime(rs.getString("endtime"));
                    tag.setStatus(rs.getInt("status"));
                    tag_Array.add(tag);
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                DBUtil.CloseDB(rs, stm, conn);
            }
            return tag_Array;
        }
        /**
         * 获取单个图书的信息,根据传入的bid来查找,返回一个BookBean数据类型
         * @param bid
         * @return
         */
        public BookBean get_BookInfo(int bid){
            BookBean tag = new BookBean();
            Connection conn = DBUtil.getConnectDb();
            String sql = "select * from book where bid="+bid;
            PreparedStatement stm = null;
            ResultSet rs = null;
            try {
                stm = conn.prepareStatement(sql);
                rs = stm.executeQuery();
                while(rs.next()){
                    tag.setBid(rs.getInt("bid"));
                    tag.setName(rs.getString("name"));
                    tag.setCard(rs.getString("card"));
                    tag.setType(rs.getString("type"));
                    tag.setAutho(rs.getString("autho"));
                    tag.setPress(rs.getString("press"));
                    tag.setNum(rs.getInt("num"));
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                DBUtil.CloseDB(rs, stm, conn);
            }
            return tag;
        }
        /**
         * 修改图书的信息,bid作为条件,
         */
        public void updateBook(int bid, String card, String name, String type, String autho, String press, int num) {
            // TODO Auto-generated method stub
            Connection conn = DBUtil.getConnectDb();
            String sql = "update book set name=?,card=?,type=?,autho=?,press=?,num=? where bid=?";
            PreparedStatement stm = null;
            try {
                stm = conn.prepareStatement(sql);
                stm.setString(1, name);
                stm.setString(2, card);
                stm.setString(3, type);
                stm.setString(4, autho);
                stm.setString(5, press);
                stm.setInt(6, num);
                stm.setInt(7, bid);
                stm.executeUpdate();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        /**
         * 删除图书信息,根据传入的bid作为条件
         * @param bid
         */
        public void deleteBook(int bid) {
            // TODO Auto-generated method stub
            Connection conn = DBUtil.getConnectDb();
            String sql = "delete from book where bid=?";
            PreparedStatement stm = null;
            try {
                stm = conn.prepareStatement(sql);
                stm.setInt(1, bid);
                stm.executeUpdate();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //System.out.println(uid);
            
        }
        /**
         * 用户查找图书,根据输入的名称,使用like进行模糊查询,然后返回一个ArrayList数组类型
         * @param name
         * @return
         */
        public ArrayList<BookBean> getLikeList(String name) {
            // TODO Auto-generated method stub
            ArrayList<BookBean> tag_Array = new ArrayList<BookBean>();
            Connection conn = DBUtil.getConnectDb();
            String sql = "select * from book where name like '%"+name+"%'";
            PreparedStatement stm = null;
            ResultSet rs = null;
            try {
                stm = conn.prepareStatement(sql);
                rs = stm.executeQuery();
                while(rs.next()){
                    BookBean tag = new BookBean();
                    tag.setBid(rs.getInt("bid"));
                    tag.setName(rs.getString("name"));
                    tag.setCard(rs.getString("card"));
                    tag.setType(rs.getString("type"));
                    tag.setAutho(rs.getString("autho"));
                    tag.setPress(rs.getString("press"));
                    tag.setNum(rs.getInt("num"));
                    tag_Array.add(tag);
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                DBUtil.CloseDB(rs, stm, conn);
            }
            return tag_Array;
        }
        /**
         * 图书借阅函数,根据传入bid图书id,adminbean当前登录用户的信息,在借阅记录数据表中新插入一条记录
         * @param bid
         * @param adminbean
         */
        public void borrowBook(int bid, AdminBean adminbean) {
            // TODO Auto-generated method stub
            BookBean bookbean = new BookBean();
            bookbean = this.get_BookInfo(bid);
            //生成日期的功能
            Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);  
            int month = c.get(Calendar.MONTH);   
            int day = c.get(Calendar.DATE);  
            //生成借阅开始日期
            String begintime = ""+year+"-"+month+"-"+day;
            month = month + 1;
            //生成截止还书日期
            String endtime = ""+year+"-"+month+"-"+day;
            Connection conn = DBUtil.getConnectDb();
            String sql = "insert  into history(aid,bid,card,bookname,adminname,username,begintime,endtime,status) values(?,?,?,?,?,?,?,?,?)";
            int rs = 0;
            PreparedStatement stm = null;
            try {
                stm = conn.prepareStatement(sql);
                stm.setInt(1, adminbean.getAid());
                stm.setInt(2, bookbean.getBid());
                stm.setString(3, bookbean.getCard());
                stm.setString(4, bookbean.getName());
                stm.setString(5, adminbean.getUsername());
                stm.setString(6, adminbean.getName());
                stm.setString(7, begintime);
                stm.setString(8, endtime);
                stm.setInt(9, 1);
                rs = stm.executeUpdate();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        /**
         * 还书功能的函数,根据传入的hid借阅记录id,讲status字段的值改为0,并将还书日期改变为当前日期
         * @param hid
         */
        public void borrowBook2(int hid) {
            // TODO Auto-generated method stub
            //生成日期
            Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);  
            int month = c.get(Calendar.MONTH);   
            int day = c.get(Calendar.DATE); 
            //生成还书日期
            String endtime = ""+year+"-"+month+"-"+day;
            Connection conn = DBUtil.getConnectDb();
            String sql = "update history set endtime=?,status=? where hid=?";
            PreparedStatement stm = null;
            try {
                stm = conn.prepareStatement(sql);
                stm.setString(1, endtime);
                stm.setInt(2, 0);
                stm.setInt(3, hid);
                stm.executeUpdate();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    其中,每次查询操作时候必须要在结束后再调用链接数据库的工具类再关闭链接,不要占用资源,对性能优化有影响,会有造成阻塞死锁的风险;

    java.sql包中的PreparedStatement 接口继承了Statement,并与之在两方面有所不同:有人主张,在JDBC应用中,如果你已经是稍有水平开发者,你就应该始终以PreparedStatement代替Statement.也就是说,在任何时候都不要使用Statement;ResultSet 为执行查询返回的结果集,结果集(ResultSet)是数据中查询结果返回的一种对象,可以说结果集是一个存储查询结果的对象,但是结果集并不仅仅具有存储的功能,他同时还具有操纵数据的功能,可能完成对数据的更新等;

  • 相关阅读:
    struts2基础
    javaEE环境搭建-eclipse
    geth
    redis常用命令
    angular-ui-select 下拉框支持过滤单选多选解决方案(系列一)
    angularjs中向html页面添加内容节点元素代码段的两种方法
    modal
    弹性布局
    自定义鼠标样式
    angularjs指令弹框点击空白处隐藏及常规方法
  • 原文地址:https://www.cnblogs.com/wmqiang/p/10558325.html
Copyright © 2020-2023  润新知