我正在尝试自学如何在java中连接到msaccess数据库。我已经设置了一个类来访问数据库,如下所示
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public abstract class AccessDBConnect2 {
public static Connection connect(){
String fileName = "C:/Users/Bridget/Documents/EmployeeSys.accdb";
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
con = DriverManager.getConnection(url,"","");
} catch (Exception e) {
// Handle exceptions ...
System.out.println(e.toString());
System.out.println("A problem accessing the database");
e.printStackTrace();
} finally {
try { if(con!=null) {con.close();} } catch (Exception e) {}
}
return con;
}
public static void closeConnection(Connection conn){
try{
conn.close();
}catch (Exception e){
}
}
然后我有我的代码,它只是试图从表中选择所有内容。我已经在msAccess中创建了表,代码似乎可以毫无问题地通过上述代码中的连接方法,表明它正在查找数据库并对其进行某种程度的访问。当我使用连接调用 prepareStatement(即代码行)时,就会出现问题:
stm = conn.prepareStatement(sql);
完整代码为:
import java.sql.*;
public class Program2{
public static void main(String[] args) {
try{
// Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// Establishing db connection
Connection conn = AccessDBConnect.connect();
// Displaying all records from employee file
System.out.println("Display records of all employees");
display(conn);
// Closing the connection
AccessDBConnect.closeConnection(conn);
}catch (Exception e){
System.out.println("Error");
}
}
// Display details of all employees
public static void display(Connection conn){
PreparedStatement stm = null;
// SQL statement
String sql = "SELECT * FROM Employee";
ResultSet rs;
try {
stm = conn.prepareStatement(sql); // Prepare the SQL statement
rs = stm.executeQuery(); // Execture the SQL statement
// Navigate through the ResultSet and print
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String address = rs.getString("address");
System.out.println("ID: t t" + id);
System.out.println("Name: t t" + name);
System.out.println("Gender: t" + gender);
System.out.println("Address: t" + address);
System.out.println(" ");
}
// Closing the resultSet
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void test(){
int a = "hello";
}
}
收到错误,因为当您尝试调用.prepareStatement
时,连接已关闭。AccessDBConnect2
类包含一个finally
块,该块在连接返回之前关闭连接。修复该类,使其保持连接打开状态。
顺便说一下,JDBC-ODBC 桥已经从 Java 8 中删除,并且实际上已经过时了。您可能对此替代方案感兴趣:
在没有 ODBC 的情况下从 Java 操作 Access 数据库
我已经删除了明显不正确的答案:)另一种可能性:
我认为问题出在您与数据库的连接上,请尝试将"C:/Users/Bridget/Documents/EmployeeSys.accdb"更改为
"C:\\Users\Bridget\Documents\EmployeeSys.accdb"