在GUI java中向表中插入新记录

时间:2015-04-15 16:13:47

标签: java mysql

我正在向mysql数据库插入一个新数据。我得到一个错误说

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '')' at
 line 1

有人能告诉我我的代码有什么问题吗?这是我的代码:

public class ButtonListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
        String queryString = "";
        String queryString2 = "";
        String outputString = "";
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/dealer", "root", "admin");
            statement = connection.createStatement();
            String driverID = driverIdTextField.getText();
            String firstName = firstNameTextField.getText();
            String lastName = lastNameTextField.getText();
            String address = addressTextField.getText();
            String phone = phoneTextField.getText();
            String license = licenseTextField.getText();
            String brand = brandTextField.getText();
            String model = modelTextField.getText();
            String year = yearTextField.getText();
            String selectItem = (String) carStatus.getSelectedItem();

            queryString = "insert into person values ('" + (driverID) + "' + '" + (firstName) + "' +  '" + (lastName) + "' + '" + (address) 
                + "' + '" + (phone) + ")";
            queryString2 = "insert into cars values ('" + (license) + "' + '" + (brand) + "' + '" + (model) + "' + '" + (year)
                + "' + '" + (selectItem) + ")";

            statement.executeUpdate(queryString);
            statement.executeUpdate(queryString2);
            connection.close();
        } catch (SQLException sqlException){
                sqlException.printStackTrace();
        } catch ( ClassNotFoundException x ) {
            x.printStackTrace();
        } catch ( InstantiationException x ) {
            x.printStackTrace();
        } catch ( IllegalAccessException x ) {
            x.printStackTrace();
        }
    }

这是我的表格。我有两张桌子

create table person
( driverID int unsigned not null primary key,
  firstName char(20) not null,
  lastName char(20) not null,
  address char(30) not null,
  phone int unsigned
);

create table cars
( license char(10) not null primary key,
  brand char(20) not null,
  model char(20) not null,
  year date,
  status char(10) not null
);

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您在INSERT语句中缺少逗号(您已使用加号)...

queryString = "insert into person values ('" + (driverID) + "', '" + (firstName) + "',  '" + (lastName) + "', '" + (address) 
            + "', '" + (phone) + "')";

(我认为你也错过了该行的近距离报价)