JDBC (Java Data Base Connectivity,java數(shù)據(jù)庫連接)是一種用于執(zhí)行SQL語句的Java API,可以為多種關(guān)系數(shù)據(jù)庫提供統(tǒng)一訪問,它由一組用Java語言編寫的類和接口組成。JDBC提供了一種基準,據(jù)此可以構(gòu)建更高級的工具和接口,使數(shù)據(jù)庫開發(fā)人員能夠編寫數(shù)據(jù)庫應用程序.
----百度百科
本文測試數(shù)據(jù)庫為university,測試表為student
SQL Server 2008
step1.數(shù)據(jù)庫的準備
開啟SQL數(shù)據(jù)庫服務:
連接數(shù)據(jù)庫后,依次進行以下三個準備步驟,如圖所示:
step2.JDBC驅(qū)動包的準備
下載后**解壓 ** sqljdbc_4.0.2206.100_chs ,然后將解壓文件夾里的 sqljdbc4.jar 導入eclipse。具體操作步驟:在所需的project右鍵選擇 properties, 再彈出的窗口里依次進行以下操作,如圖所示:
注:最后要勾選**zip,jar **選項。
step3.測試
在該project里新建test.java類,用測試代碼進行測試:
出現(xiàn)已經(jīng)連上數(shù)據(jù)庫 和測試結(jié)果證明成功連接。
測試代碼如下,注意紅框內(nèi)內(nèi)容因人而異:
package pk1;
import java.sql.*;
public class test {
public static void main(String[] args) {
String url="jdbc:sqlserver://localhost:1433; DatabaseName=university";
String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
Statement st;
Connection con;
try{
Class.forName(driver);
}
catch(ClassNotFoundException event){System.out.print("無法創(chuàng)建驅(qū)動程式實體!");}
try{
con=DriverManager.getConnection(url,"sa","123456");
con.setAutoCommit(true);
System.out.println("已經(jīng)連接到數(shù)據(jù)庫...");
st=con.createStatement();
ResultSet rs=st.executeQuery("SELECT * from student ");
while(rs.next())
{ String name=rs.getString("stu_name");
System.out.println(name);
}
st.close();
con.close();
}
catch(SQLException e1) {System.out.println("異常"+e1);}
}
}
MySQL
step1.JDBC驅(qū)動包的準備
無需解壓可直接導入eclipse,與上面SQL Server step2操作方式相同。
step2.測試
在該project里新建test.java類,用測試代碼進行測試,注意一定要以run as application 運行:
出現(xiàn)兩條success語句即Success loading Mysql Driver! 和 Success connect Mysql server! 和測試結(jié)果證明成功連接。(測試結(jié)果里第二行為warning不影響結(jié)果)
測試代碼如下,注意紅框內(nèi)內(nèi)容因人而異:
import java.sql.*;
public class test {
public static void main(String args[]) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Success loading Mysql Driver!");
}
catch (Exception e) {
System.out.print("Error loading Mysql Driver!");
e.printStackTrace();
}
try {
Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306?serverTimezone=UTC","root","123456");
System.out.println("Success connect Mysql server!");
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("select * from university.student");
while (rs.next()) {
System.out.println("查詢的同學的學號是:");
System.out.println(rs.getString("stu_num"));
}
}
catch (Exception e) {
System.out.print("get data error!");
e.printStackTrace();
}
}
}
更新:鑒于CSDN上傳資源總是有bug,已將資源轉(zhuǎn)到百度云盤,這里有一篇關(guān)于如何繞過百度網(wǎng)盤客戶端下載大文件的文章,幫助我們不受云盤限速影響,更方便的下載資源,歡迎大家嘗試。文章鏈接:
http://www.lxweimin.com/p/6cced261a094