import java.sql.*;
/**
* <p>Title: ODBC連接數據庫</p>
* <p>Description: 本實例演示如何使用JDBC-ODBC橋操作數據庫。</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: odbcConn.java</p>
* @version 1.0
*/
public class odbcConn{
private String url="";
private String username="";
private String password="";
/**
*<br>方法說明:獲得數據連接
*<br>輸入參數:
*<br>返回類型:Connection 連接對象
*/
public Connection conn(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, username, password);
return con;
}catch(SQLException sqle){
System.out.println("can´t connection db:"+sqle);
return null;
} catch (Exception e) {
System.out.println("Failed to load JDBC/ODBC driver.");
return null;
}
}
/**
*<br>方法說明:執行查詢SQL語句
*<br>輸入參數:Connection con 數據庫連接
*<br>輸入參數:String sql 要執行的SQL語句
*<br>返回類型:
*/
public void query(Connection con, String sql){
try{
if(con==null) return;
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rmeta = rs.getMetaData();
int numColumns = rmeta.getColumnCount();
while(rs.next())
{
for(int i = 0;i< numColumns;i++)
{
String sTemp = rs.getString(i+1);
System.out.print(sTemp+" ");
}
System.out.println("");
}
}catch(Exception e){
System.out.println("query error:"+e);
}finally{
try{
con.close();
}catch(SQLException se){}
}
}
/**
*<br>方法說明:執行插入、更新、刪除等沒有返回結果集的SQL語句
*<br>輸入參數:Connection con 數據庫連接
*<br>輸入參數:String sql 要執行的SQL語句
*<br>返回類型:
*/
public void execute(Connection con, String sql){
try{
if(con==null) return;
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
}catch(Exception e){
System.out.println("query error:"+e);
}finally{
try{
con.close();
}catch(SQLException se){}
}
}
/**
*<br>方法說明:主方法
*<br>輸入參數:
*<br>返回類型:
*/
public static void main(String[] arg){
if(arg.length!=3){
System.out.println("use: java odbcConn url username password");
return;
}
odbcConn oc = new odbcConn();
oc.url = arg[0];
oc.username=arg[1];
oc.password=arg[2];
oc.execute(oc.conn(),"insert into userinfo(name,address)values(´switch´,´new York´)");
oc.query(oc.conn(),"select * from userinfo");
}
}