java 中數據庫連接的JDBC和驅動程序的深入分析。本站提示廣大學習愛好者:(java 中數據庫連接的JDBC和驅動程序的深入分析)文章只能為提供參考,不一定能成為您想要的結果。以下是java 中數據庫連接的JDBC和驅動程序的深入分析正文
java 中數據庫連接的JDBC和驅動程序的深入分析
理解:
java應用程序與數據庫建立連接時,先通過jdbc(jdbc是屬於jdk帶有的)與數據庫廠商提供的驅動程序通信,而驅動程序再與數據庫通信。
數據庫廠商提供的驅動程序:
數據庫的種類有多種,比如mysql、oracle等,不同的數據庫有不同的驅動程序。所以在進行其他操作前,首先要下載導入對應的驅動程序jar包。
連接測試步驟:
先聲明所用到的數據庫的url、用戶名和密碼(數據庫的)
private static String url="jdbc:mysql://localhost:3306/mydb"; private static String name="root"; private static String password="1234";
1.載入驅動程序
2.使用connect與數據庫建立連接
載入驅動程序有兩種方式:
public static void main(String[] args) {
try {
//載入驅動程序
Class.forName("com.mysql.jdbc.Driver");
//使用connect與數據庫建立連接
Connection connection=(Connection) DriverManager.getConnection(url,name,password);
System.out.println("數據庫連接成功");
} catch (Exception e) {
System.out.println("數據庫連接失敗");
e.printStackTrace();
}
}
或者:
public static void main(String[] args) {
try {
//載入驅動程序
Driver driver=new Driver();
DriverManager.registerDriver(driver);//
//使用connect與數據庫建立連接
Connection connection=(Connection) DriverManager.getConnection(url,name,password);
System.out.println("數據庫連接成功");
} catch (Exception e) {
System.out.println("數據庫連接失敗");
e.printStackTrace();
}
}
輸出:
數據庫連接成功
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!