zoukankan      html  css  js  c++  java
  • JDBC工具类封装

    封装

    package util;
     
    import java.sql.Connection; 
    import java.sql.DriverManager; 
    import java.sql.PreparedStatement; 
    import java.sql.ResultSet; 
    import java.sql.SQLException; 
       
    /**
     * @author sawyer 2014下午1:20:16
     * 
     */ 
       
    public class JdbcUtil { 
        private Connection conn = null; 
        private PreparedStatement stmt = null; 
        private ResultSet rs = null; 
        private static String driver = "com.mysql.jdbc.Driver"; 
        private String url = "jdbc:mysql://localhost:3306/Student"; 
        private String user = "root"; 
        private String password = "root"; 
       
        /**
         * Get the driver
         */ 
        static { 
       
        } 
        /**
         * Connect the database
         */ 
        public Connection getCon() { 
            try { 
                Class.forName(driver); 
            } catch (ClassNotFoundException e) { 
                e.printStackTrace(); 
            } 
            try { 
                conn = (Connection) DriverManager 
                        .getConnection(url, user, password); 
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } 
            return conn; 
        } 
       
        /**
         * @param sql
         * @param obj
         *Update
         */
        public int update(String sql, Object... obj) {
            int count = 0;
            conn = getCon();
            try {
                stmt = conn.prepareStatement(sql);
                if (obj != null) {
                    for (int i = 0; i < obj.length; i++) {
                        stmt.setObject(i + 1, obj[i]);
                    }
                }
                count = stmt.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                close();
            }
            return count;
        }
      
        /**
         * @param sql
         * @param obj
         * Query
         */
        public ResultSet Query(String sql, Object... obj) {
            conn = getCon();
            try {
                stmt = conn.prepareStatement(sql);
                if (obj != null) {
                    for (int i = 0; i < obj.length; i++) {
                        stmt.setObject(i + 1, obj[i]);
                    }
                }
                rs = stmt.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
               // close();
            }
            return rs;
        }
       
        /**
         * CLose the resource
         */ 
        public void close() { 
            try { 
                if (rs != null) { 
                    rs.close(); 
                } 
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } finally { 
                try { 
                    if (stmt != null) { 
                        stmt.close(); 
                    } 
                } catch (SQLException e) { 
                    e.printStackTrace(); 
                } finally { 
                    if (conn != null) { 
                        try { 
                            conn.close(); 
                        } catch (SQLException e) { 
                            e.printStackTrace(); 
                        } 
                    } 
                } 
            } 
        } 
    }

    model

    package model;
     
    import java.io.Serializable;
     
    public class Student implements Serializable{
        private int id;
        private int age;
        private String name;
         
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }

    测试

    package model;
     
    import java.sql.ResultSet;
    import java.sql.SQLException;
     
    import util.JdbcUtil;
     
    public class Test {
        public static void main(String[] args) {
            testInsert();
            testQuery();
        }
        public static void testInsert(){
            Student s=new Student();
            s.setId(12);
            s.setAge(23);
            s.setName("xxt");
            JdbcUtil u=new JdbcUtil();
            String sql="insert into T_Student(id,age,name) values( ?,?,?)";
            int result=u.update(sql, s.getId(),s.getAge(),s.getName());
            System.out.println(result);
        }
        public static void testQuery(){
            String sql="select * from T_Student where age=?";
            Student s=new Student();
            s.setAge(23);
            JdbcUtil u=new JdbcUtil();
            ResultSet rs=u.Query(sql, s.getAge());
            try {
                while(rs.next()){
                    //s.setName(rs.getString("name"));
                    System.out.println(rs.getString("name"));//s.getName(rs.getString("name"))
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

     调用原生的方式:

     
                    Connection conn=util.getCon();
    		String sql="select * from "+tableName+" where date=?";
    		log.info("sql:"+sql);
    		PreparedStatement stmt = null;
    		try {
    			stmt = conn.prepareStatement(sql);
    		} catch (SQLException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    		try {
    			stmt.setString(1, date);
    		} catch (SQLException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    		
    		ResultSet rs = null;
    		try {
    			rs = stmt.executeQuery();
    		} catch (SQLException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    
    

      需要注意的是,query方法如果不需要参数查全部的话,直接填null

    ResultSet rs=util.Query(sqlStr,null);

  • 相关阅读:
    一步一步学grails:7 MVC
    虚拟机安装CentOS7
    虚拟机安装windows sever2008
    微信console
    centOS7常用操作命令
    lr事务
    2.0通信之调用ADO.NET Data Services(数据服务)
    Silverlight应用程序中如何获取ASP.NET页面参数
    2.0网页之可脚本化, 与DOM的交互, 与JavaScript的交互
    2.0Tip/Trick之MessageBox, Popup, 循环的几种实现方法, 动态变换主题, 本地化(多语言), 响应鼠标双击事件
  • 原文地址:https://www.cnblogs.com/JAYIT/p/6876035.html
Copyright © 2011-2022 走看看