1. 程式人生 > >通過JDBC連線SQLSEVER資料庫

通過JDBC連線SQLSEVER資料庫

  與連線MySql配製相似,只是JDBC的驅動不同,下面只是簡單例子,實際開發中應該把實現資料庫連線的程式碼封裝起來,然後通過函式呼叫得到Connection.

testsql2k.java

import java.sql.*;
/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: Bule Tytle Work Stdio</p>
 *
 * @author awolf168
 * @version 1.0
 */
public class testsql2k {
    public testsql2k() {
}

    public static void main(String args[])
   {
    Connection con;
    Statement st;
    ResultSet re;
    String url,driver;
        //driver="com.microsoft.jdbc.sqlserver.SQLServerDriver";
        url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=fortest";
        try{
            Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
           // System.out.print("class");
            con=DriverManager.getConnection(url,"test","test");  //使用者名稱 , 密碼
            //System.out.print("con");
            st=con.createStatement();
            re=st.executeQuery("select * from  DEPARTMENT");
            while(re.next())
            {
              System.out.println("Connected Sqlsever2k..."+re.getString("系號")+"    "+re.getString("系名"));
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        try {
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    
   }
}