JAVA與資料庫連接方法

來源:互聯網
上載者:User

用JAVA串連資料庫主要有兩種方式,一是用JDBC-ODBC橋來串連,二是用相關廠商提供的相應驅動程式來串連,首先談談第一種串連。

JDBC-ODBC橋接器是用JdbcOdbc.Class和一個用於訪問ODBC驅動程式的本地庫實現的。對於WINDOWS平台,該本地庫是一個動態串連庫DLL

(JDBCODBC.DLL)。

由於JDBC在設計上與ODBC很接近。在內部,這個驅動程式把JDBC的方法映射到ODBC調用上,這樣,JDBC就可以和任何可用的ODBC驅動程式進行

互動了。這種橋接器的優點是,它使JDBC目前有能力訪問幾乎所有的資料庫。通行方式如圖所示:

應用程式---JDBC API---JDBC-ODBC---ODBC API---ODBC層---資料來源

具體操作方法為:

首先開啟控制台的管理工具,開啟資料來源(ODBC),在使用者DSN裡面添加資料來源(即你要串連的資料庫的名字),在這裡假定串連SQL SERVER

2000的GoodsSupply資料庫。名稱填寫你要串連的資料庫的名稱(GoodsSupply),然後逐步設定,如果選用了使用SQL-SERVER密碼認證的話,

就要輸入相應的使用者名稱及密碼串連到資料庫。一路下一步設定完成。

在JAVA裡面編寫程式進行測試,在這裡我的程式是讓使用者輸入任意的表名與與列名,把該列的所有資料輸出。原始碼如下:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.*;

public class ODBCBridge {

public static void main(String[] args) {
String url="jdbc:odbc:GoodsSupply";
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 {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //載入驅動
}catch(ClassNotFoundException e){
System.out.println("Can not load Jdbc-Odbc Bridge Driver");
System.err.print("ClassNotFoundException:");
System.err.println(e.getMessage());
}
Connection con=DriverManager.getConnection(url,"USER","PASSWORD"); //使用SQL-SERVER2000認證
DatabaseMetaData dmd=con.getMetaData(); //DMD為串連的相應情況
System.out.println("串連的資料庫:"+dmd.getURL());
System.out.println("驅動程式:"+dmd.getDriverName());
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(SQLException ex) {
System.out.println("SQLException:");
while(ex!=null) {
System.out.println("Message:"+ex.getMessage());
ex=ex.getNextException();
}
}catch(Exception e) {
System.out.println("IOException");
}
}


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

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

這種實現方法是直接使用資料庫廠商提供的用專用的網路通訊協定建立的驅動程式,通過它可以直接將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();
}
}
}

 


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

最後給出JAVA串連其他資料庫的關鍵代碼:

1、Oracle8/8i/9i資料庫(thin模式)   
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();   
String  url="jdbc:oracle:thin:@localhost:1521:orcl";   
//orcl為資料庫的SID   
String  user="test";   
String  password="test";   
Connection  conn=  DriverManager.getConnection(url,user,password);   
 
2、DB2資料庫   
Class.forName("com.ibm.db2.jdbc.app.DB2Driver  ").newInstance();   
String  url="jdbc:db2://localhost:5000/sample";   
//sample為你的資料庫名   
String  user="admin";   
String  password="";   
Connection  conn=DriverManager.getConnection(url,user,password);    
 
3、Sybase資料庫   
Class.forName("com.sybase.jdbc.SybDriver").newInstance();   
String  url  ="  jdbc:sybase:Tds:localhost:5007/myDB";   
//myDB為你的資料庫名   
Properties  sysProps  =  System.getProperties();   
SysProps.put("user","userid");   
SysProps.put("password","user_password");   
Connection  conn=  DriverManager.getConnection(url,  SysProps);   
 
4、Informix資料庫   
Class.forName("com.informix.jdbc.IfxDriver").newInstance();   
String  url  =   
"jdbc:informix-sqli://123.45.67.89:1533/myDB:INFORMIXSERVER=myserver;   
user=testuser;password=testpassword";   
//myDB為資料庫名   
Connection  conn=  DriverManager.getConnection(url);   
 
5、MySQL資料庫   
Class.forName("org.gjt.mm.mysql.Driver").newInstance();   
String  url  ="jdbc:mysql://localhost/myDB?user=soft&password=soft1234&useUnicode= 
true&characterEncoding=8859_1"   
//myDB為資料庫名   
Connection  conn=  DriverManager.getConnection(url);   
 
6、PostgreSQL資料庫   
Class.forName("org.postgresql.Driver").newInstance();   
String  url  ="jdbc:postgresql://localhost/myDB"   
//myDB為資料庫名   
String  user="myuser";   
String  password="mypassword";   
Connection  conn=  DriverManager.getConnection(url,user,password);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.