1. 程式人生 > 實用技巧 >JDBC 2—— 獲取資料庫連線

JDBC 2—— 獲取資料庫連線

方式一:

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
      testConnection1();
    }

  //方式一:
    public static void testConnection1() throws SQLException {
        // 1、註冊驅動
        Driver driver = new com.mysql.jdbc.Driver();
        
// url:http//localhost:8080/gmall/keyboard.jpg // jdbc:mysql:協議 // 3360:預設mysql的埠號 // test:test資料庫 String url = "jdbc:mysql://localhost:3306/MySQL"; Properties info = new Properties(); // 將使用者名稱和密碼封裝在Propect中 info.setProperty("user", "root"); info.setProperty(
"password", "root"); Connection coon = driver.connect(url, info); System.out.println(coon); }

方式二:

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

      testConnection2();
    }

  //方式二:對方式一的迭代
public static void testConnection2() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException{ //1、獲取Driver實現類物件,使用反射 Class clazz = Class.forName("com.mysql.jdbc.Driver"); Driver driver = (Driver) clazz.newInstance(); //2、提供要連線的資料庫 String url = "jdbc:mysql://localhost:3306/MySQL"; //3、提供連線需要的使用者名稱和密碼 Properties info = new Properties(); info.setProperty("user", "root"); info.setProperty("password", "root"); //4、獲取連線 Connection coon = driver.connect(url, info); System.out.println(coon); }