1. 程式人生 > >jdbc篇第4課:封裝Dbc

jdbc篇第4課:封裝Dbc

  這節課開始我們開始講封裝jdbc

 

  分析:

在前面幾課中,我們都要先建立連線,獲取Connection物件,而且程式碼是重複的,我們可以將這部分程式碼提取出來

 

  實現:

package com.tool;



import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;



//Database Connection,負責連線資料庫,返回一個Connection物件

public class 
Dbc {     //不允許呼叫構造器     private Dbc(){}     public static Connection getConnection(String driver,String url,String user, String password) throws ClassNotFoundException, SQLException {         Class.forName(driver)
;         return DriverManager.getConnection(url,user,password);     } }

 

  測試程式碼:

public static void main(String[] args) throws SQLException, ClassNotFoundException {

    String driver = "com.mysql.jdbc.Driver";

    
String url = "jdbc:mysql://localhost:3306/teach";     String user = "root";     String password = "root";     Connection conn = Dbc.getConnection(driver, url, user, password);     //測試下連線是否真的可用     Statement statement = conn.createStatement();     String sql = "select * from tbl_employee where id = 1";     ResultSet resultSet = statement.executeQuery(sql);     resultSet.next();     System.out.println(resultSet.getInt(1));     System.out.println(resultSet.getString(2));     //連線確實可用 }

 

  結果:

1

xiaoye