Java訪問ACCESS數(shù)據(jù)庫的方法
這里采用的是配置ODBC數(shù)據(jù)源的方式。
所以首先需要進行數(shù)據(jù)源的配置工作:
創(chuàng)建ODBC過程:
控制面板-->管理工具--〉數(shù)據(jù)源。
選擇“系統(tǒng)DSN”--〉“添加”
選擇“driver do Microsoft Access”,點擊“完成”
給數(shù)據(jù)源起個名字,例如accessTest.
點擊“選擇”,選擇你的數(shù)據(jù)庫文件即可。
這樣就配置了一個數(shù)據(jù)源。
下面是訪問數(shù)據(jù)庫的一個例子:
package com.hf.accessTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ConnectionManager {
static {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection con=null;
//String url = "jdbc:odbc:driver={Microsoft Access Driver(*.mdb)};DBQ=f:\\test.mdb";
String url=new String("jdbc:odbc:accessTest");//test時資料來源
try {
con= DriverManager.getConnection(url);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
/**
* @param args
*/
public static void main(String[] args) {
//得到連接
Connection con = ConnectionManager.getConnection();
try {
PreparedStatement st = con.prepareStatement("select id,name from test1 ");
ResultSet rs = st.executeQuery();
while (rs.next()){
String id");
String name");
System.out.println("id:"+id+" name: "+name );
}
rs.close();
st.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
就簡單為大家介紹的到這里,其實還有很多別的方法,這只是其中之一,如果大家對這個比較感興趣,以后還會為大家介紹更好更多的方法。
【編輯推薦】