Java串連SQLServer 2008資料庫的步驟:
1.到微軟官方下載jdbc 並解壓,得到sqljdbc.jar和sqljdbc4.jar,由於使用的是JDK1.7,所以使用sqljdbc4.jar,
2.複製檔案sqljdbc4.jar到jdk目錄\jdk1.7.0\jre\lib\ext下。
配置系統變數classpath 變數路徑 D:\Java\jdk1.7.0\jre\lib\ext\sqljdbc4.jar
測試程式:
複製代碼 代碼如下:
import java.sql.*;
public class T1{
public static void main(String []args)
{
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("成功載入SQL驅動程式");
}
catch(Exception e){
System.out.println("找不到SQL驅動程式");
}
System.out.println("hello huuuu!!");
}
}
3.開始-〉程式-〉sql server 2008-〉組態工具-〉SQL Server Configuration Manager。啟動sql 2008服務。點擊 sql server2008網路設定節點,並選中”SQLserver的協議“節點。
啟用tcp/ip協議,將IP地址中的IPALL TCP連接埠設定為1433,然後到服務中重啟 SQLServer(很重要啊。。。)。
測試程式:
複製代碼 代碼如下:
import java.sql.*; public class T2{
public static void main(String []args)
{
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); System.out.println("成功載入SQL驅動程式");
}
catch(Exception e){
System.out.println("找不到SQL驅動程式");
}
try{
Connectioncon=DriverManager.getConnection"jdbc:sqlserver://localhost:1433;
DatabaseName=SQLTest", "sa","123");
Statement stmt = con.createStatement(); System.out.println("資料庫連接成功");
}
catch(Exception e){
System.out.println("資料庫連接失敗"); }
}
}
注意上述程式中的DatabaseName,需要先在資料庫中建立名為SQLTest的資料庫。然後再開始串連。
好了,經過上述的配置和測試,以後就可以用Java對資料庫進行操作。