从java插入数据到ms访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20090994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert data to ms access from java
提问by Hazim Ali
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:
我是 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)
code:
代码:
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");
}
采纳答案by Java Man
you have not installed driver for MSAccess properly..
您没有正确安装 MSAccess 驱动程序..
For example try like this..
例如尝试这样..
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 ,"","");
And also make sure that you have import jar file of ODBC driver in your path..
并确保您的路径中有 ODBC 驱动程序的导入 jar 文件..
Update :
更新 :
Insert data like this..
像这样插入数据..
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();