com.microsoft.sqlserver.jdbc.SQLServerException: Socket closed 或者 該連接已關閉


com.microsoft.sqlserver.jdbc.SQLServerException: Socket closed 或者 該連接已關閉

解決方案:

 

 DBUtil公共方法如下:

  1 package com.dao;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.sql.*;
  6 import java.text.ParsePosition;
  7 import java.text.SimpleDateFormat;
  8 import java.util.ArrayList;
  9 import java.util.Calendar;
 10 import java.util.Date;
 11 import java.util.List;
 12 import java.util.Properties;
 13 
 14 import com.fasterxml.jackson.core.JsonParseException;
 15 import com.fasterxml.jackson.core.JsonProcessingException;
 16 import com.fasterxml.jackson.databind.JsonMappingException;
 17 import com.fasterxml.jackson.databind.ObjectMapper;
 18 
 19 public class DBUtil {
 20     //連接對象
 21     //Statement 命令對象
 22     //打開連接
 23     //關閉連接
 24     //得到一個連接對象
 25     //查詢(有參,無參)
 26     //修改(有參,無參)
 27     static Statement stmt = null;
 28     //驅動,服務器地址,登錄用戶名,密碼    
 29     static String DBDRIVER;
 30     static String DBURL;
 31     static String DBUID;
 32     static String DBPWD;
 33     
 34     static {
 35         //先創建資源文件,擴展名為.properties
 36         //內容是以:dbuser=sa  格式
 37         
 38         Properties prop = new Properties();//先獲取資源對象
 39         //創建輸入流,讀取資源文件
 40         InputStream in =Thread.currentThread().getContextClassLoader()
 41                 .getResourceAsStream("jdbc.properties");
 42         try {
 43             prop.load(in);//加載
 44             DBDRIVER = prop.getProperty("DBDRIVER");
 45             DBURL = prop.getProperty("DBURL");
 46             DBUID = prop.getProperty("DBUID");
 47             DBPWD = prop.getProperty("DBPWD");
 48             //System.out.println(DBDRIVER);
 49         } catch (IOException e) {
 50             System.out.println("資源文件讀取錯誤,請查看資源文件");
 51         } 
 52         try {
 53             in.close();
 54         } catch (IOException e) {
 55             e.printStackTrace();
 56         }
 57     }
 58     //打開連接
 59      static  {
 60         //加載驅動
 61         try {
 62             Class.forName(DBDRIVER);
 63         } catch (ClassNotFoundException e) {
 64             e.printStackTrace();
 65         }
 66     }
 67     //關閉連接
 68     public static void close(Connection conn) {
 69         try {
 70             if(stmt!=null)
 71                     stmt.close();
 72             if(conn!=null && !conn.isClosed())
 73                 conn.close();
 74         } catch (SQLException e) {
 75             // TODO Auto-generated catch block
 76             e.printStackTrace();
 77         }
 78     }
 79     public static void close(ResultSet rs) {
 80         Statement st = null;
 81         Connection con = null;
 82         try {
 83             try {
 84                 if (rs != null) {
 85                     st = rs.getStatement();
 86                     rs.close();
 87                 }
 88             } finally {
 89                 try {
 90                     if (st != null) {
 91                         con = st.getConnection();
 92                         st.close();
 93                     }
 94                 } finally {
 95                     if (con != null) {
 96                         con.close();
 97                     }
 98                 }
 99             }
100         } catch (SQLException e) {
101             e.printStackTrace();
102         }
103     }
104     //得到一個連接對象,當用戶使用DBUtil無法解決個性問題時
105     //可以通過本方法獲得連接對象
106     public static Connection getConnection() {
107          Connection conn = null;
108         try {
109             conn=DriverManager.getConnection(DBURL,DBUID,DBPWD);
110         } catch (SQLException e) {
111             e.printStackTrace();
112         }
113         return conn;
114     }
115     
116     //executeQuery
117     //executeUpdate
118     //execute
119     //獲得查詢的數據集
120     //select * from student where name='' and sex=''
121     public static ResultSet executeQuery(String sql) {
122         Connection conn = getConnection();
123         try {
124             stmt = conn.createStatement();
125             return stmt.executeQuery(sql);
126         } catch (SQLException e) {
127             // TODO Auto-generated catch block
128             e.printStackTrace();
129         }
130         return null;
131     }
132     
133     //修改表格內容
134     public static int executeUpdate(String sql) {
135         Connection conn = getConnection();
136         int result = 0;
137         try {
138             stmt = conn.createStatement();
139             result = stmt.executeUpdate(sql);
140         } catch (SQLException e) {
141             // TODO Auto-generated catch block
142             e.printStackTrace();
143         } finally {
144             close(conn);
145         }
146         return result;
147     }
148     //如果執行的查詢或存儲過程,會返回多個數據集,或多個執行成功記錄數
149     //可以調用本方法,返回的結果,
150     //是一個List<ResultSet>或List<Integer>集合
151     public static Object execute(String sql) {
152         Connection conn = getConnection();
153         boolean b=false;
154         try {
155             stmt = conn.createStatement();
156             b = stmt.execute(sql);            
157             //true,執行的是一個查詢語句,我們可以得到一個數據集
158             //false,執行的是一個修改語句,我們可以得到一個執行成功的記錄數
159             if(b){
160                 return stmt.getResultSet();
161             }
162             else {
163                 return stmt.getUpdateCount();
164             }
165         } catch (SQLException e) {
166             // TODO Auto-generated catch block
167             e.printStackTrace();
168         } finally {
169             if(!b) {
170                 close(conn);
171             }
172         }
173         return null;
174     }
175     
176     //
177     //select * from student where name=? and sex=?
178     public static ResultSet executeQuery(String sql,Object[] in) {
179         Connection conn = getConnection();
180         try {
181             PreparedStatement pst = conn.prepareStatement(sql);
182             for(int i=0;i<in.length;i++)
183                 pst.setObject(i+1, in[i]);
184             stmt = pst;//只是為了關閉命令對象pst
185             return pst.executeQuery();
186         } catch (SQLException e) {
187             // TODO Auto-generated catch block
188             e.printStackTrace();
189         }
190         return null;
191     }
192     
193     public static int executeUpdate(String sql,Object[] in) {
194         Connection conn = getConnection();
195         try {
196             PreparedStatement pst = conn.prepareStatement(sql);
197             for(int i=0;i<in.length;i++)
198                 pst.setObject(i+1, in[i]);
199             stmt = pst;//只是為了關閉命令對象pst
200             return pst.executeUpdate();
201         } catch (SQLException e) {
202             // TODO Auto-generated catch block
203             e.printStackTrace();
204         }finally {
205             close(conn);
206         }
207         return 0;
208     }
209     public static Object execute(String sql,Object[] in) {
210         Connection conn = getConnection();
211         boolean b=false;
212         try {
213             PreparedStatement pst = conn.prepareStatement(sql);
214             for(int i=0;i<in.length;i++)
215                 pst.setObject(i+1, in[i]);
216             b = pst.execute();
217             //true,執行的是一個查詢語句,我們可以得到一個數據集
218             //false,執行的是一個修改語句,我們可以得到一個執行成功的記錄數
219             if(b){
220                 System.out.println("----");
221                 /*List<ResultSet> list = new ArrayList<ResultSet>();
222                 list.add(pst.getResultSet());
223                 while(pst.getMoreResults()) {
224                     list.add(pst.getResultSet());
225                 }*/
226                 return pst.getResultSet();
227             }
228             else {
229                 System.out.println("****");
230                 List<Integer> list = new ArrayList<Integer>();
231                 list.add(pst.getUpdateCount());
232                 while(pst.getMoreResults()) {
233                     list.add(pst.getUpdateCount());
234                 }
235                 return list;
236             }
237         } catch (SQLException e) {
238             // TODO Auto-generated catch block
239             e.printStackTrace();
240         } finally {
241             if(!b) {
242                 System.out.println("====");
243                 close(conn);
244             }
245         }
246         return null;
247     }
248     //調用存儲過程  proc_Insert(?,?,?)
249     public static Object executeProcedure(String procName,Object[] in) {
250         Connection conn = getConnection();
251         try {
252             procName = "{call "+procName+"(";
253             String link="";
254             for(int i=0;i<in.length;i++) {
255                 procName+=link+"?";
256                 link=",";
257             }
258             procName+=")}";
259             CallableStatement cstmt = conn.prepareCall(procName);
260             for(int i=0;i<in.length;i++) {
261                 cstmt.setObject(i+1, in[i]);
262             }
263             if(cstmt.execute())
264             {
265                 return cstmt.getResultSet();
266             }
267             else {
268                 return cstmt.getUpdateCount();
269             }
270         } catch (SQLException e) {
271             // TODO Auto-generated catch block
272             e.printStackTrace();
273         }
274         
275         return null;
276     }
277     
278 
279     /*
280      * 調用存儲過程,並有輸出參數
281      * @procName ,存儲過程名稱:proc_Insert(?,?)
282      * @in ,輸入參數集合
283      * @output,輸出參數集合
284      * @type,輸出參數類型集合
285      * */
286     public static Object executeOutputProcedure(String procName,
287             Object[] in,Object[] output,int[] type){
288         Connection conn = getConnection();
289         Object result = null;
290         try {
291             CallableStatement cstmt = conn.prepareCall("{call "+procName+"}");
292             //設置存儲過程的參數值
293             int i=0;
294             for(;i<in.length;i++){//設置輸入參數
295                 cstmt.setObject(i+1, in[i]);
296                 //print(i+1);
297             }
298             int len = output.length+i;
299             for(;i<len;i++){//設置輸出參數
300                 cstmt.registerOutParameter(i+1,type[i-in.length]);
301                 //print(i+1);
302             }
303             boolean b = cstmt.execute();
304             //獲取輸出參數的值
305             for(i=in.length;i<output.length+in.length;i++)
306                 output[i-in.length] = cstmt.getObject(i+1);
307             if(b) {
308                 result = cstmt.getResultSet();
309             }
310             else {
311                 result = cstmt.getUpdateCount();
312             }
313         } catch (SQLException e) {
314             // TODO Auto-generated catch block
315             e.printStackTrace();
316         }
317         return result;
318     }
319     public static String toJson(Object obj){
320         String reuqest=null;
321         //對象映射
322         ObjectMapper mapper=new ObjectMapper();
323         //設置時間格式
324         SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy年MM月dd日");
325         mapper.setDateFormat(dateFormat);
326             try {
327                 reuqest=mapper.writeValueAsString(obj);
328             } catch (JsonProcessingException e) {
329                 // TODO Auto-generated catch block
330                 e.printStackTrace();
331             }
332         return reuqest;
333     }
334     public static <T> T toObject(String src,Class<T> valueType){
335         T request=null;
336             //對象反射
337           ObjectMapper mapper=new ObjectMapper();
338           try {
339             request=mapper.readValue(src, valueType);
340         } catch (JsonParseException e) {
341             // TODO Auto-generated catch block
342             e.printStackTrace();
343         } catch (JsonMappingException e) {
344             // TODO Auto-generated catch block
345             e.printStackTrace();
346         } catch (IOException e) {
347             // TODO Auto-generated catch block
348             e.printStackTrace();
349         }
350         return request;
351     }
352     public static Date date(String date_str) {
353         try {
354             Calendar zcal = Calendar.getInstance();//日期類
355             Timestamp timestampnow = new Timestamp(zcal.getTimeInMillis());//轉換成正常的日期格式
356             SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");//改為需要的東西
357             ParsePosition pos = new ParsePosition(0);
358             java.util.Date current = formatter.parse(date_str, pos);
359             timestampnow = new Timestamp(current.getTime());
360             return timestampnow;
361         }
362         catch (NullPointerException e) {
363             return null;
364         }
365     }
366 }

  聲明:使用該公共方法需要在WEB-INF/classes/jdbc.properties添加連接驅動等等 如圖:

 

在classes中加入鏈接

 

1 DBDRIVER=com.microsoft.sqlserver.jdbc.SQLServerDriver
2 DBURL=jdbc:sqlserver://localhost:1433;databasename=AJAX_ProductDB
3 DBUID=sa
4 DBPWD=123456

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM