JAVA與資料庫連接方法(二)

來源:互聯網
上載者:User

    現在介紹第二種方法,用關廠商提供的相應驅動程式來串連。

    這種實現方法是直接使用資料庫廠商提供的用專用的網路通訊協定建立的驅動程式,通過它可以直接將JDBC API調用轉換為直接網路調用。這種調用方式一般效能比較好,而且也是實用中最簡單的方法。因為它步需要安裝其他的庫或中介軟體。幾乎所有的資料庫廠商都為他們的資料庫提供了這種資料庫提供了這種JDBC驅動程式,也可以從第三方廠商獲得這些驅動程式。

    從網址http://industry.Java.sun.com/products/jdbc/drivers/可以看到所有有用的驅動程式的清單。其結果:

    應用程式---JDBC API---驅動程式---資料來源

    這裡首先要安裝JDBC的驅動程式,推薦SP2版本的,可從微軟網站上下載
    http://www.microsoft.com/downloads/details.aspx?FamilyID=9f1874b6-f8e1-4bd6-947c-0fc5bf05bf71&DisplayLang=en 下載最下面的SETUP.EXE

    這個驅動程式要配合SQL SERVER2000 SP3A,相應下載URL為
    http://www.microsoft.com/china/sql/downloads/sp3.asp 下載 chs_sql2ksp3.exe

    如果用JAVA SDK直接編譯啟動並執行話需要設定環境變數,將安裝好的JDBC驅動裡面的LIB三個檔案設定為環境變數:
    classpath: 
    D:/program  files/Microsoft  SQL  Server/jdbc/lib/msbase.jar;
    D:/program  files/Microsoft  SQL  Server/jdbc/lib/mssqlserver.jar;
    D:/program  files/Microsoft  SQL  Server/jdbc/lib/msutil.jar;

    安裝即可用微軟的驅動程式串連資料庫了,相應代碼與前面基本相同:

import java.sql.*;
import java.io.*;
public class DBColumn {

 public static void main(String[] args) {
  Connection con=null;
  Statement sm=null;
  String command=null;
  ResultSet rs=null;
  String tableName=null;
  String cName=null;
  String result=null;
  BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
  try
  {
   Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
   System.out.println("驅動程式已載入");
   //SQL SERVER的登陸方式必須為使用SQL SERVER密碼登陸認證方式
   con=DriverManager.getConnection("jdbc:microsoft:sqlserver://SERVERNAME:1433","USER","PASSWORD"); 
   con.setCatalog("GoodsSupply");
   System.out.println("OK,成功串連到資料庫");
  }catch(Exception ex) {
   ex.printStackTrace();
  }
  try
  {
   sm=con.createStatement();
   System.out.println("輸入表名");
   tableName=input.readLine();
   while(true) {
    System.out.println("輸入列名(為空白時程式結束):");
    cName=input.readLine();
    if(cName.equalsIgnoreCase(""))
     break;
    command="select "+cName+" from "+tableName;
    rs=sm.executeQuery(command);
    if(!rs.next())
     System.out.println("表名或列名輸入有誤");
    else {
     System.out.println("查詢結果為:");
     do
     {
      result=rs.getString(cName);
      //result=new String(result.getBytes("ISO-8859-1"),"GB2312");
      System.out.println(result);
     }while(rs.next());
    }
   }
  }catch(Exception ex) {
   ex.printStackTrace();
  }
 }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.