-->

插入数据从Java中的MS Access(Insert data to ms access from

2019-10-19 00:26发布

我是新来的JDBC。 我想将数据插入到从Java访问,但我不能得到它。 它显示了以下错误:

Connection Established Successfully  
java.sql.SQLException: General error  
Could Not Connect to Database  
    at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)  
    at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)  
    at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)  
    at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)  
    at sun.jdbc.odbc.JdbcOdbcStatement.executeUpdate(Unknown Source)  
    at DBConnect.<init>(DBConnect.java:22)  
    at DBConnect.main(DBConnect.java:32)  

码:

public DBConnect() {
    File f = new File("DB.accdb");
    try{
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        System.out.println("DriverLoaded");
        String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + f.getAbsolutePath();
        Connection con = DriverManager.getConnection(url);
        System.out.println("Connection Established Successfully");

        Statement st=con.createStatement();
        String productId="1";
        String desc="Jambu";
        int quantity=10;
        double price = 2.0, disc=1.0;
        st.executeUpdate("INSERT into Product(productID,description,quantity,price,discount) VALUES('"+productId+"','"+desc+"','"+quantity+"','"+price+"','"+disc+"')");
        System.out.println("Row is added");
    }catch(Exception e) {
        e.printStackTrace();
        System.out.println("Could Not Connect to Database");
    }

Answer 1:

你有没有为MSACCESS安装的驱动程序正确..

例如尝试这样的..

   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  // set this to a MS Access DB you have on your machine
   String filename = "d:/DB.accdb";
   String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=";
   database+= filename.trim() + ";DriverID=22;}"; // add on to the end 
   // now we can get the connection from the DriverManager
   Connection con = DriverManager.getConnection( database ,"",""); 

并确保您有ODBC驱动程序的进口jar文件在你的路径..

更新:

插入这样的数据..

PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("insert into product(productID,description,quantity,price,discount) values(?,?,?,?,?)");
           pstmt.setString(1, productId);
           pstmt.setString(1, desc);
           //same for all statement
           pstmt.executeUpdate();
           pstmt.close();


文章来源: Insert data to ms access from java