資料庫連接代碼模板__資料庫

來源:互聯網
上載者:User

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 資料庫連接類
 */

public class BaseDao {

 //2005的驅動串連
 //com.microsoft.sqlserver.jdbc.SQLServerDriver
 //jdbc:sqlserver://localhost:1433;databasename=company
 
 //  2000的驅動串連
 //com.microsoft.jdbc.sqlserver.SQLServerDriver
 //jdbc:microsoft:sqlserver://localhost:1433;databasename=company
 
 //資料庫驅動
 private final static String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
 // URL
 private final static String URL="jdbc:sqlserver://localhost:1433;DataBaseName=databaseName";
 //資料庫使用者名稱
 private final static String DBNAME="sa";
 //資料庫密碼
 private final static String DBPASS="sa"; 
 
 /**
  * 得到資料庫連接
  * @return 資料庫連接
  * @throws ClassNotFoundException
  * @throws SQLException
  */
 public static Connection getConn() throws ClassNotFoundException,SQLException{
  Class.forName(DRIVER); //註冊驅動
  Connection conn=DriverManager.getConnection(URL,DBNAME,DBPASS);
  return conn;
 }
 
 /**
  * 關閉資料庫相關串連
  * @param conn
  * @param pstmt
  * @param rs
  */
 public static void closeAll(Connection conn,PreparedStatement pstmt,ResultSet rs){
  /*如果rs不空,關閉rs*/
  if(rs!=null){
   try{
    rs.close();
   }catch(SQLException e){
    e.printStackTrace();
   }
  }
  
  /*如果pstmt不空,關閉pstmt*/
  if(pstmt!=null){
   try{
    pstmt.close();
   }catch(SQLException e){
    e.printStackTrace();
   }
  }
  
  /*如果conn不空,關閉conn*/
  if(conn!=null){
   try{
    conn.close();
   }catch(SQLException e){
    e.printStackTrace();
   }
  }
 }
 /**
  * 執行SQL語句,可以進行增、刪、改、的操作,不能執行查詢
  * @param preparedSql 先行編譯的 SQL 陳述式
  * @param param 先行編譯的SQL語句中的'?'參數的字串數組
  * @return 影響的條數
  */
 public static int executeSQL(String preparedSql,String[] param){
  Connection conn=null;
  PreparedStatement pstmt=null;
  int num=0;
  /*處理SQL,執行SQL*/
  try{
   conn=getConn();  //得到資料庫連接
   pstmt=conn.prepareStatement(preparedSql);
   if(param!=null){
    for(int i=0;i<param.length;i++){
     pstmt.setString(i+1, param[i]); //設定參數
    }
   }
   num=pstmt.executeUpdate(); //執行SQL語句
  }catch(ClassNotFoundException e){
   e.printStackTrace(); //處理ClassNotFountException異常
  }catch(SQLException e){
   e.printStackTrace(); //處理SQLException異常
  }finally{
   closeAll(conn,pstmt,null); //釋放資源
  }
  return num;
 }  
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.