java - 从java向ms access插入数据

标签 java sql ms-access jdbc jdbc-odbc

我是 JDBC 新手。我想从 Java 将数据插入到 Access 中,但无法获取。它显示以下错误:

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");
    }

最佳答案

您尚未正确安装 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();

关于java - 从java向ms access插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20090994/

相关文章:

java - 在MySql数据库中创建表时,遇到NullPointerException

mysql - mysql 错误(错误 1136)

mysql - 选择左连接上的最后一条记录 mysql

mysql - 错误: OLE DB provider "MSDASQL' ' for Linked Server '' bequick'' was unable to begin a Distributed transaction

java - 怎么解决?。线程 "main"java.lang.UnsatisfiedLinkError : Can't find dependent libraries 中出现异常

java - 在 JLabel 中显示数学序列

asp.net - 多列条件计数 SQL

ms-access - 如何通过匹配 ID 折叠 MS Access 表行

java - PropertiesConfiguration - 在属性值中使用 "/"

forms - 使用文本框自动滚动到底部