从Java向MS Access插入数据 [英] Insert data to ms access from java

查看:129
本文介绍了从Java向MS Access插入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to JDBC. I want to insert data into Access from Java, but I can't get it. It shows the following error:

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驱动程序.

you have not installed driver for MSAccess properly..

例如,尝试这样.

   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文件.

And also make sure that you have import jar file of ODBC driver in your path..

更新:

像这样插入数据.

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向MS Access插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆