连接ACCESS数据库

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* @author E-mail:
* @version 创建时间:Dec 2, 2008 9:33:23 AM
* 连接access数据库
*/
public class ConnectAccess {
public static void main(String[] args) {
try {
// Load JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//String path = URLDecoder.decode(ConnectAccess.class.getResource("/").getPath()
// + "db1.mdb", "UTF-8");
//System.out.println(path);
// DBQ可以绝对路径,也可以是相对路径,相对路径见下面
//StrinString dbUrl = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=" + path;
String dbUrl = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=c:/db1.mdb";
Connection con = DriverManager.getConnection(dbUrl, "", "");
Statement stmt = con.createStatement();
// 执行SQL语句
String sql = "select * from test";

ResultSet rs = stmt.executeQuery(sql);
// 打印测试
if (rs != null) {
while (rs.next()) {
System.out.println("\t" + rs.getString("住址"));
}
rs.close();
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

------------------------------------------------------------------

String realpath = "data/database.mdb"; //数据库文件相对的位置
String dbpath = application.getRealPath(realpath); //由相对位置得出绝对路径
System.out.println(dbpath);
String url="jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ="+dbpath;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection(url);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

你可能感兴趣的:(java,sql,jdbc,Microsoft,Access)