Question

I have a "Syntax error in INSERT INTO statement". Here is a copy code (the code is in a JFrame which I created using the GUI builder FYI):

private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {                                            
    String InputTeam1, InputTeam2;
    Integer InputTeam1Goals, InputTeam2Goals;

    FixtureNumber = Integer.parseInt(jLabel3.getText());

    InputTeam1 = jComboBox1.getSelectedItem() + "";
    InputTeam2 = jComboBox2.getSelectedItem() + "";
    InputTeam1Goals = Integer.parseInt(jTextField2.getText());
    InputTeam2Goals = Integer.parseInt(jTextField3.getText());

    try
    {
        String filename = "Database.mdb";
        String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
        database += filename.trim() + ";DriverID=22;READONLY=false";
        conn = DriverManager.getConnection(database, "", "");

        Statement sta = conn.createStatement();
      //Line below is the INSERT statement
        int s = sta.executeUpdate("INSERT INTO tblLeagueFixtures VALUES '" + InputTeam1 + "', '" + InputTeam2 + "', '" + InputTeam1Goals + "', '" + InputTeam2Goals + "' WHERE FixtureNumber = '"+ FixtureNumber +"'");
        System.out.println("Inserted into database.");
    }
    catch (Exception e3)
    {
        System.out.println("Exception ReadPlayerStats:" + e3);
    }
}

The purpose of the code is to get data (Team1 etc) from the user and then insert it into the database. I have tried changing apostrophe's, putting WHERE before VALUES etc but the result is the same. The error persists whether I am inserting new data or updating existing data.

[SOLVED]

int s = sta.executeUpdate("UPDATE tblLeagueFixtures SET [Team1] = '"+ InputTeam1 +"', [Team2] = '"+ InputTeam2 +"', [Team1Goals] = "+ InputTeam1Goals +", [Team2Goals] = "+ InputTeam2Goals +" WHERE [FixtureNumber] = "+ FixtureNumber);
Was it helpful?

Solution

You have at least 2 issues in your INSERT command.

1) You can't use WHERE clause in INSERT INTO VALUES statement.

2) In the INSERT INTO VALUES statement the values must appear in brackets.

int s = sta.executeUpdate("INSERT INTO tblLeagueFixtures VALUES ('" + InputTeam1 + "', '" + InputTeam2 + "', '" + InputTeam1Goals + "', '" + InputTeam2Goals + "')");

To update data you must use correct syntax. For more information refer to this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top