写入Access DB

时间:2015-07-06 11:26:19

标签: java ms-access

我试图将一些数据写入MS-Access数据库但我不断获取"未知来源"错误。下面的堆栈跟踪:

java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.
    at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
    at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
    at sun.jdbc.odbc.JdbcOdbc.SQLExecute(Unknown Source)
    at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(Unknown Source)
    at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeUpdate(Unknown Source)
    at SampleDB.main(SampleDB.java:15)

以下代码示例:

import java.sql.*;

public class SampleDB {
    public static void main (String[]args) {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
        Connection con = DriverManager.getConnection("jdbc:odbc:sample_db"); 
            PreparedStatement ps = con.prepareStatement("INSERT INTO Data_Sample (FirstName,Surname,Address) (?,?,?)");
            ps.setString(1,"John");
            ps.setString(2,"Smith");
        ps.setString(3,"New York");

            ps.executeUpdate();
            con.close();    
            System.out.println("inserted");
        } catch(Exception e) {
            e.printStackTrace();
        }

    }
}

感谢您在调试上述任何帮助。

2 个答案:

答案 0 :(得分:3)

您的插入查询错误

INSERT INTO Data_Sample (FirstName,Surname,Address) (?,?,?)

应该是

INSERT INTO Data_Sample(FirstName,Surname,Address) values(?,?,?)

答案 1 :(得分:0)

问题是SQL语句的格式格式错误。

应该是

 PreparedStatement ps = con.prepareStatement("INSERT INTO Data_Sample (FirstName,Surname,Address) VALUES (?,?,?)");