我想教自己如何連接到java中的msaccess數據庫。 我已經建立了一個類,然後如下java.sql.SQLException:無效的句柄
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";
}
}
非常感謝你,最後是問題所在。 這是一個明顯的錯誤,只會讓你瘋狂幾個小時。 我將看看Java 8中JDBC-ODBC的替代方案。 再次感謝 – Bridget 2014-11-30 16:00:23