Java訪問(wèn)ACCESS數(shù)據(jù)庫(kù)的方法
這里采用的是配置ODBC數(shù)據(jù)源的方式。
所以首先需要進(jìn)行數(shù)據(jù)源的配置工作:
創(chuàng)建ODBC過(guò)程:
控制面板-->管理工具--〉數(shù)據(jù)源。
選擇“系統(tǒng)DSN”--〉“添加”
選擇“driver do Microsoft Access”,點(diǎn)擊“完成”
給數(shù)據(jù)源起個(gè)名字,例如accessTest.
點(diǎn)擊“選擇”,選擇你的數(shù)據(jù)庫(kù)文件即可。
這樣就配置了一個(gè)數(shù)據(jù)源。
下面是訪問(wèn)數(shù)據(jù)庫(kù)的一個(gè)例子:
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時(shí)資料來(lái)源
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();
就簡(jiǎn)單為大家介紹的到這里,其實(shí)還有很多別的方法,這只是其中之一,如果大家對(duì)這個(gè)比較感興趣,以后還會(huì)為大家介紹更好更多的方法。
【編輯推薦】