package com.mytest;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PReparedStatement;import java.sql.ResultSet;import java.util.Vector;public class DBUtil { //定義連接數據庫需要的 Connection ct=null; PreparedStatement pS=null; ResultSet rS=null; public ResultSet getSlect(String sql,Object ...params){ Vector rowDate=new Vector(); Vector columnDate =new Vector(); try { ct = connectWithDB(); pS=ct.prepareStatement(sql); for(int i = 0;i < params.length;i++){ pS.setObject(i+1, params[i]); } rS=pS.executeQuery(); } catch (Exception e) { // TODO: handle exception }finally{ return rS; } } /************修改數據庫操作*********************/ public int update(String sql,Object ...params){ int executeUpdate_int = 0; try { ct = connectWithDB(); pS=ct.prepareStatement(sql); for(int i = 0;i < params.length;i++){ pS.setObject(i+1, params[i]); } //執行操作 executeUpdate_int = pS.executeUpdate(); } catch (Exception e) { // TODO: handle exception }finally{ shutDownDB(); return executeUpdate_int; } } /************連接數據庫*********************/ private Connection connectWithDB(){ Connection connection = null; try { //加載驅動 Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); connection = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;databaseName=spdb","sa","123456"); } catch (Exception e) { // TODO: handle exception } return connection; } /************關閉數據庫的相關連接*********************/ public void shutDownDB(){ try { if(rS!=null) rS.close(); if(pS!=null) pS.close(); if(ct!=null) ct.close(); } catch (Exception e2) { e2.printStackTrace(); // TODO: handle exception } } }
新聞熱點
疑難解答