我试图自学如何连接到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中创建了表,代码似乎通过上面代码中的connect方法没有任何问题,表明它正在查找数据库并稍微访问它。当我使用连接调用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";
}
}
答案 0 :(得分:2)
您收到错误,因为当您尝试呼叫.prepareStatement
时,连接已关闭。您的AccessDBConnect2
类包含一个finally
块,它在返回之前关闭连接。修复该类,使连接保持打开状态。
顺便说一下,JDBC-ODBC Bridge已从Java 8中删除,并且实际上已经过时了。您可能对此替代方案感兴趣:
答案 1 :(得分:-1)
我删除了明显不正确的答案:)另一种可能性:
我认为问题出在您与数据库的连接上,请尝试将'C:/Users/Bridget/Documents/EmployeeSys.accdb'更改为'C:\\ Users \ Bridget \文档\ EmployeeSys.accdb'