Search code examples
javajdbcfoxprodbfvisual-foxpro

Syntax error in an insert on dbf table


i am trying to make an insert on a dbf table using jdbc, but every time that i execute the system give me this error:

Exception in thread "main" java.sql.SQLException: [Microsoft][ODBC Visual FoxPro Driver]Syntax error.
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.executeQuery(Unknown Source)
at addProduct.test.main(test.java:29)

This is the code:

public static void main(String[] args) throws ClassNotFoundException, SQLException {
    // TODO Auto-generated method stub
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String connString="jdbc:odbc:Driver={Microsoft Visual FoxPro Driver};SourceDB=C:\\RestBar\\DBC;SourceType=DBF";//DeafultDir indicates the location of the db
    Connection connection=DriverManager.getConnection(connString);
    Statement query = connection.createStatement();

    ResultSet result;
    String sql="INSERT INTO CUENTAS (NUM_CTA, NUB_CTA, CAJ_CTA, FEC_CTA, HOR_CTA, " +
            "OPE_CTA, MES_CTA, NOM_CTA, UBI_CTA, PER_CTA, ACU_CTA, USU_CTA, KDI_CTA) " +
            "VALUES('0000001', SELECT DES_MEZ FROM MESAS WHERE COD_MEZ = 'T01', '01', " +
            "'2013/07/18', '16:50:33', 0,'002', SELECT DES_MES FROM MESEROS WHERE COD_MES = '002'," +
            " 'T01', '2',0.00, 01, 0.00)";
    query.execute(sql);


}

Solution

  • If you want to use subqueries, you need to use them as part of a SELECT, not as part of the scalar values you list in VALUES. And FoxPro does not allow a SELECT without a FROM.

    Your simplified query follows (note that you'll want to remove the line breaks or insert semicolons to wrap the string when you send it to VFP):

    INSERT INTO CUENTAS (
        NUM_CTA, 
        NUB_CTA, 
        CAJ_CTA, FEC_CTA, HOR_CTA, OPE_CTA, MES_CTA, 
        NOM_CTA, 
        UBI_CTA, PER_CTA, ACU_CTA, USU_CTA, KDI_CTA
    ) 
    SELECT
        '0000001', 
        DES_MEZ , 
        '01', '2013/07/18', '16:50:33', 0,'002', 
        (SELECT DES_MES FROM MESEROS WHERE COD_MES = '002'), 
        'T01', '2',0.00, 01, 0.00
    FROM MESAS WHERE COD_MEZ = 'T01'
    

    Note that when writing an INSERT...SELECT statement, adding proper column names to the SELECT is valid and good practice.