码迷,mamicode.com
首页 > 数据库 > 详细

JDBC连接sql server数据库操作

时间:2015-09-04 22:31:22      阅读:482      评论:0      收藏:0      [点我收藏+]

标签:

1、首先,先创建一个连接数据库的工具类:

 1 package gu.db.util;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 
 6 public class ConnectionFactory {
 7     public static Connection getConnection(String url,String name,String passwd){
 8         Connection con = null;
 9         String className = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
10         try{
11             Class.forName(className);
12             con = DriverManager.getConnection(url, name, passwd);
13         }catch(Exception e){
14             e.printStackTrace();
15         }
16     
17         return con;
18     }
19 }

2、抽象父类dao:

 

 1 package gu.db.dao;
 2 
 3 import gu.db.helper.HelpConstants;
 4 import gu.db.util.ConnectionFactory;
 5 import gu.model.basis.AbstractData;
 6 
 7 import java.sql.Connection;
 8 import java.sql.ResultSet;
 9 import java.sql.ResultSetMetaData;
10 import java.sql.Statement;
11 import java.util.ArrayList;
12 
13 public abstract class AbstractDao {
14     protected String url = "jdbc:sqlserver://localhost:1433;databasename = Task";
15     protected String username = "sa";
16     protected String passwd = "";
17     
18     public String editRecords(ArrayList<AbstractData> datas){
19         ArrayList<AbstractData> addList = new ArrayList<AbstractData>();
20         ArrayList<AbstractData> deleteList = new ArrayList<AbstractData>();
21         ArrayList<AbstractData> updateList = new ArrayList<AbstractData>();
22         int count = datas.size();
23         for(int index = 0;index < count ;index++){
24             AbstractData data = datas.get(index);
25             byte operCode = data.getOper_code();
26             if(operCode == HelpConstants.ADD){
27                 addList.add(data);
28             }else if(operCode == HelpConstants.DELETE){
29                 deleteList.add(data);
30             }else if(operCode == HelpConstants.UPDATE){
31                 updateList.add(data);
32             }
33         }        
34         int add = addRecords(addList);
35         int delete = deleteRecords(deleteList);
36         int update = updateRecords(updateList);
37         StringBuffer buffer = new StringBuffer();
38         buffer.append("成功添加"+add+"条记录,成功删除"+delete+"条记录,成功修改"+update+"条记录");
39         return buffer.toString();
40         
41     }
42     
43     public String[] getColumnNames(String sql){
44         String[] columnNames = null;
45         Connection con = null;
46         Statement state = null;
47         ResultSet rs = null;
48         try{
49             con = ConnectionFactory.getConnection(url, username, passwd);
50             state =con.createStatement();
51             rs = state.executeQuery(sql);
52             ResultSetMetaData rsmd = rs.getMetaData();
53             int size = rsmd.getColumnCount();
54             columnNames = new String[size];
55             for(int i = 0;i < size;i++){
56                 columnNames[i] = rsmd.getColumnLabel(i+1);
57             }
58         }catch(Exception e){
59             e.printStackTrace();
60         }finally{
61             try{
62                 if(rs != null){
63                     rs.close();
64                 }
65                 if(state != null){
66                     state.close();
67                 }
68                 if(con != null){
69                     con.close();
70                 }
71             }catch(Exception ex){
72                 ex.printStackTrace();
73             }
74             
75         }
76         return columnNames;
77     }
78     
79     public abstract int addRecords(ArrayList<AbstractData> datas);
80     public abstract int deleteRecords(ArrayList<AbstractData> datas);
81     public abstract int updateRecords(ArrayList<AbstractData> datas);
82 }

 

 

 

3、以User类为例:

  1 package gu.db.dao;
  2 
  3 import gu.db.util.ConnectionFactory;
  4 import gu.model.basis.AbstractData;
  5 import gu.model.login.User;
  6 
  7 import java.sql.Connection;
  8 import java.sql.PreparedStatement;
  9 import java.sql.ResultSet;
 10 import java.sql.Statement;
 11 import java.util.ArrayList;
 12 
 13 public class UserDao extends AbstractDao {
 14 
 15     @Override
 16     public int addRecords(ArrayList<AbstractData> datas) {
 17         // TODO Auto-generated method stub
 18         int amount = 0;
 19         Connection con = null;
 20         PreparedStatement psmt = null;
 21         String sql = "insert into users (user_name,user_passwd,user_role) values (?,?,?)";
 22         try{
 23             con = ConnectionFactory.getConnection(url, username, passwd);
 24             psmt = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
 25             boolean old = con.getAutoCommit();
 26             con.setAutoCommit(false);
 27             int size = datas.size();
 28             for(int index = 0;index < size;index++){
 29                 User user = (User) datas.get(index);
 30                 psmt.setString(1, user.getUser_name());
 31                 psmt.setString(2, user.getUser_passwd());
 32                 psmt.setByte(3, user.getUser_role());
 33                 psmt.addBatch();
 34             }
 35             int[] result = psmt.executeBatch();
 36             con.commit();
 37             con.setAutoCommit(old);
 38             
 39             for(int i = 0;i < result.length;i++){
 40                 amount += result[i];
 41             }
 42         }catch(Exception e){
 43             try{
 44                 amount = 0;
 45                 con.rollback();
 46             }catch(Exception ex){
 47                 ex.printStackTrace();
 48             }
 49             e.printStackTrace();
 50         }finally{
 51             try{
 52                 if(psmt != null){
 53                     psmt.close();
 54                 }
 55                 if(con != null){
 56                     con.close();
 57                 }
 58             }catch(Exception e){
 59                 e.printStackTrace();
 60             }
 61         }
 62         return amount;
 63     }
 64 
 65     @Override
 66     public int deleteRecords(ArrayList<AbstractData> datas) {
 67         // TODO Auto-generated method stub
 68         int amount = 0;
 69         Connection con = null;
 70         PreparedStatement psmt = null;
 71         String sql = "delete users where user_name = ?";
 72         try{
 73             con = ConnectionFactory.getConnection(url, username, passwd);
 74             psmt = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
 75             boolean old = con.getAutoCommit();
 76             con.setAutoCommit(false);
 77             int count = datas.size();
 78             for(int index = 0;index < count;index++){
 79                 User user = (User)datas.get(index);
 80                 psmt.setString(1, user.getUser_name());
 81                 psmt.addBatch();
 82             }
 83             int[] result = psmt.executeBatch();
 84             con.commit();
 85             con.setAutoCommit(old);
 86             
 87             for(int i = 0;i < result.length;i++){
 88                 amount += result[i];
 89             }
 90         }catch(Exception e){
 91             try{
 92                 amount = 0;
 93                 con.rollback();
 94             }catch(Exception ex){
 95                 ex.printStackTrace();
 96             }
 97             e.printStackTrace();
 98         }finally{
 99             try{
100                 if(psmt != null){
101                     psmt.close();
102                 }
103                 if(con != null){
104                     con.close();
105                 }
106             }catch(Exception e){
107                 e.printStackTrace();
108             }
109         }
110         return amount;
111     }
112 
113     @Override
114     public int updateRecords(ArrayList<AbstractData> datas) {
115         // TODO Auto-generated method stub
116         int amount = 0;
117         Connection con = null;
118         PreparedStatement psmt = null;
119         String sql = "update users set user_passwd = ?,user_role = ? where user_name = ?";
120         try{
121             con = ConnectionFactory.getConnection(url, username, passwd);
122             psmt = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
123             boolean old = con.getAutoCommit();
124             con.setAutoCommit(false);
125             int count = datas.size();
126             for(int index = 0;index < count;index++){
127                 User user = (User)datas.get(index);
128                 psmt.setString(1, user.getUser_passwd());
129                 psmt.setByte(2, user.getUser_role());
130                 psmt.setString(3, user.getUser_name());
131                 psmt.addBatch();
132             }
133             int[] result = psmt.executeBatch();
134             con.commit();
135             con.setAutoCommit(old);
136             
137             for(int i = 0;i < result.length;i++){
138                 amount += result[i];
139             }
140         }catch(Exception e){
141             try{
142                 amount = 0;
143                 con.rollback();
144             }catch(Exception ex){
145                 ex.printStackTrace();
146             }
147             e.printStackTrace();
148         }finally{
149             try{
150                 if(psmt != null){
151                     psmt.close();
152                 }
153                 if(con != null){
154                     con.close();
155                 }
156             }catch(Exception e){
157                 e.printStackTrace();
158             }
159         }
160         return amount;
161     }
162     //登录验证
163         public User anthenticate(String name,String pw,byte role){
164             User user = null;
165             Connection con = null;
166             Statement state = null;
167             ResultSet rs = null;
168             String sql = "select user_name,user_passwd,user_role from users where user_name = \‘" + name + "\‘ " +
169                     "and user_passwd = \‘" + pw + "\‘ " +
170                             "and user_role = \‘" + role + "\‘";
171             try{
172                 con = ConnectionFactory.getConnection(url, username, passwd);
173                 state = con.createStatement();
174                 rs = state.executeQuery(sql);
175                 if(rs.next()){
176                     user = new User(rs.getString(1),rs.getString(2),rs.getByte(3)); //验证成功,产生对象
177                 }
178             }catch(Exception e){
179                 e.printStackTrace();
180             }finally{
181                 try{
182                     if(rs != null){
183                         rs.close();
184                     }
185                     if(state != null){
186                         state.close();
187                     }
188                     if(con != null){
189                         con.close();
190                     }
191                 }catch(Exception e){
192                     e.printStackTrace();
193                 }
194             }
195             return user;
196         }
197         
198         public ArrayList<User> getUsers(){
199             ArrayList<User> users = new ArrayList<User>();
200             Connection con = null;
201             Statement state = null;
202             ResultSet rs = null;
203             String sql = "select * from users";
204             
205             try{
206                 con = ConnectionFactory.getConnection(url, username, passwd);
207                 state = con.createStatement();
208                 rs = state.executeQuery(sql);
209                 while(rs.next()){
210                     User user = new User(rs.getString(1),rs.getString(2),rs.getByte(3));
211                     users.add(user);
212                 }
213             }catch(Exception e){
214                 e.printStackTrace();
215             }finally{
216                 try{
217                     if(rs != null){
218                         rs.close();
219                     }
220                     if(state != null){
221                         state.close();
222                     }
223                     if(con != null){
224                         con.close();
225                     }
226                 }catch(Exception e){
227                     e.printStackTrace();
228                 }
229             }
230             return users;
231         }
232         
233         public String[] ColumnNames(String[] names){
234             String[] columnNames = new String[names.length+3];
235             for(int i = 0;i < names.length;i++){
236                 columnNames[i] = names[i];
237             }
238             columnNames[names.length] = "添加";
239             columnNames[names.length+1] = "删除";
240             columnNames[names.length+2] = "修改";
241             return columnNames;
242         }
243 }

 

JDBC连接sql server数据库操作

标签:

原文地址:http://www.cnblogs.com/0519xf/p/4782409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!