JDBC操作MySQL数据

对原始jdbc进行封装

  1 package com.utils;
  2 
  3 import java.sql.Connection;
  4 import java.sql.DriverManager;
  5 import java.sql.PreparedStatement;
  6 import java.sql.ResultSet;
  7 import java.sql.ResultSetMetaData;
  8 import java.sql.SQLException;
  9 import java.util.ArrayList;
 10 import java.util.HashMap;
 11 import java.util.List;
 12 import java.util.Map;
 13 import java.util.Properties;
 14 
 15 /**
 16  * DButil.java
 17  * @author zl
 18  * @version 1.0
 19  * 功能介绍:使用jdbc对数据库操作(查询、更新(插入/修改/删除)、批量更新)
 20  */
 21 public class DButil {
 22     
 23     private Connection conn = null;            //jdbc的链接
 24     private PreparedStatement ps = null;    //准备sql
 25     
 26     /**
 27      * 无参构造方法
 28      */
 29     public DButil(){}
 30     
 31     /*
 32      * @param 无
 33      * 功能介绍:加载驱动,连接数据库。
 34      */
 35     public Connection getConnection(){
 36         //准备好jdbc文件承载的类
 37         Properties properties = new Properties();
 38         try {
 39             //装载jdbc文件到承载类
 40             properties.load(DButil.class.getResourceAsStream("jdbc.properties"));
 41             //取承载类的属性
 42             String driverClassName = properties.getProperty("driverClassName");    //mysql的驱动
 43             String url = properties.getProperty("url");    //数据库的url
 44             String username = properties.getProperty("username");    //数据库的用户名
 45             String pwd = properties.getProperty("pwd");    //数据库当前用户的密码
 46             Class.forName(driverClassName);
 47             conn = DriverManager.getConnection(url,username,pwd);    //获取conn链接
 48             return conn;
 49         } catch (Exception e) {
 50             e.printStackTrace();
 51         }
 52         return null;
 53     }
 54     
 55     /*
 56      * @param sql,params 
 57      * 功能介绍:更新操作(修改,删除,插入)
 58      */
 59     public int executeUpdate(String sql,Object[] params){
 60         
 61         try {
 62             ps = conn.prepareStatement(sql);
 63             if(params.length != 0){
 64                 for(int i=0; i<params.length; i++){
 65                     ps.setObject(i+1, params[i]);
 66                 }
 67             }
 68             int rows = ps.executeUpdate();
 69             return rows;
 70         } catch (Exception e) {
 71             e.printStackTrace();
 72         }finally{
 73             closeUpdate();
 74         }
 75         return 0;
 76     }
 77     
 78     /*
 79      * @param:
 80      * 功能介绍:批量更新
 81      */
 82     public void batchUpdate(String sql,List<Object[]> list){
 83         
 84          try {  
 85                 ps = conn.prepareStatement(sql);  
 86                 conn.setAutoCommit(false); //关闭mysql自动提交事务
 87                 //final int batchSize = 1000;    //防止内存溢出
 88                 //int count = 0;    //记录插入数量
 89                 int size = list.size();  
 90                 Object[] obj = null;  
 91                 for (int i = 0; i < size; i++) {  
 92                     obj = list.get(i);  
 93                     for (int j = 0; j < obj.length; j++) {  
 94                         ps.setObject(j + 1, obj[j]);  
 95                     }  
 96                     ps.addBatch();
 97                     /*if(++count % batchSize == 0) {
 98                         ps.executeBatch();
 99                         //conn.commit();
100                     }*/
101                 }  
102                 ps.executeBatch();  
103                 conn.commit();  
104                 conn.setAutoCommit(true);  
105             } catch (SQLException e) {  
106                 e.printStackTrace();  
107                 try {  
108                     conn.rollback();  
109                     conn.setAutoCommit(true);  
110                 } catch (SQLException e1) {  
111                     e1.printStackTrace();  
112                 }  
113             } finally {  
114                 closeUpdate();    //关闭资源
115             }  
116     }
117     
118     /*
119      * @param sql,params
120      * 功能介绍:查询操作
121      */
122     public List<Map<String,String>> executeQuery(String sql,Object[] params){
123          
124         ResultSet rs = null;
125         List<Map<String,String>> list = null;
126         try {
127             ps = conn.prepareStatement(sql);
128             if(params != null){
129                 for(int i=0; i<params.length; i++){
130                     ps.setObject(i+1,params[i]);
131                 }
132             }
133             rs = ps.executeQuery();
134             list = new ArrayList<Map<String,String>>();
135             while(rs.next()){    //移动光标,如果新的当前行有效,则返回 true;如果不存在下一行,则返回 false
136                 ResultSetMetaData rsmd = rs.getMetaData();
137                 Map<String,String> map = new HashMap<String, String>();
138                 for(int i=1; i<=rsmd.getColumnCount(); i++){
139                     map.put(rsmd.getColumnName(i),rs.getObject(i).toString());
140                 }
141                 list.add(map);
142             }
143             return list;
144             
145         } catch (Exception e) {
146             e.printStackTrace();
147         }finally{
148             closeQuery(rs);
149         }
150         return null;
151     }
152     
153     /*
154      * @param 无
155      * 功能介绍:关闭更新资源
156      */
157     public void closeUpdate(){
158         try{
159             if(ps!=null){
160                 ps.close();
161             }
162             
163             if(conn!=null){
164                 conn.close();
165             }
166         }catch(SQLException e){
167             e.printStackTrace();
168         }
169     }
170     
171     /*
172      * @param rs
173      * 功能介绍:关闭查询资源
174      */
175     public void closeQuery(ResultSet rs){
176         try {
177             if(rs!=null){
178                 rs.close();
179             }
180             
181             if(ps!=null){
182                 ps.close();
183             }
184             
185             if(conn!=null){
186                 conn.close();
187             }
188         } catch (SQLException e) {
189             e.printStackTrace();
190         }
191     }
192     
193     /*
194      * @param: args 
195      * 功能介绍:测试jdbc 
196      */
197     /*public static void main(String[] args) {
198         
199         DButil db = new DButil();
200         db.getConnection();
201 //        String sql = "select * from cpu2006 where id=?";
202 //        Object[] params = new Object[1];
203 //        params[0] = 1;
204 //        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
205 //        list = db.executeQuery(sql, params);
206 //        System.out.println(list.toString());
207             String sql2 = "insert into cpu2006(hardware_vendor,cores,chips,cores_per_chip,base_copies,result,baseline,publish,sys)values(?,?,?,?,?,?,?,?,?)";
208             List<Object[]> inList = new ArrayList<Object[]>();    //需要新增的数据
209            Object[] cpu = new Object[]{"1","1","1","1","1","1","1","1","1"};
210            inList.add(cpu);
211            db.batchUpdate(sql2, inList);
212     }*/
213 
214 }

 附上

jdbc.properties
1 driverClassName=com.mysql.jdbc.Driver
2 url=jdbc:mysql://localhost:3306/testMysql?useUnicode=true&amp;characterEncoding=utf-8
3 username=root
4 pwd=root
View Code

 

posted @ 2017-09-22 11:35  云绮石  阅读(223)  评论(0编辑  收藏  举报