java读取ACCESS数据库的简单示例
虽然简单,对初学者来说,如果没有一段可以成功执行的代码供参考,还真难调试
先用ACCESS建一个数据库 DB1.MDB,里面有一表"table1",内有字段"Name"和"Age"
随便填几条记录,保存后到ODBC里建一个系统数据源"Access2000"连上此数据库
然后就可以用下面的代码显示数据库里的所有记录了
database.java
------------------
import java.sql.*;
class database {
public static void main(String args[]) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:Access2000";
Connection connection=DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sql="Select * FROM table1";
ResultSet rs = statement.executeQuery(sql);
String tt;
while (rs.next()) {
System.out.print("姓名:" + rs.getString("Name"));
System.out.println(" 年龄:" + rs.getString("Age"));
}
rs.close();
connection.close();
}
catch(Exception ex){
System.out.println(ex);
System.exit(0);
}
}
}
------------
OK,编译运行:
E:\java>javac database.java
E:\java>java database
第二种方法
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class AccessJdbc {
public static void main(String[] args) {
Connection conn = null;
Statement ps = null;
ResultSet rs = null;
try {
// Access注册驱动
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// url地址(*.mdb, *.accdb)括号内容中间"逗号"后面要有空格
String url = "jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\Administrator\\Desktop\\11.accdb";
conn = DriverManager.getConnection(url);
ps = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = ps.executeQuery("select * from test");
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
ps.close();
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}