简体   繁体   English

尝试使用Java写入数据库时​​SQL语法错误

[英]Error in SQL syntax when trying to write to the database with Java

I'm working with mvc in java to connect to a database. 我正在使用Java中的mvc连接数据库。 The setData methord seams to not be working and not sure why. setData方法似乎无法正常工作,并且不确定原因。 My database is called checker and the table info. 我的数据库称为检查器和表信息。 connection works fine and can read data from db to textfields but when I place data into textfields I get an error. 连接工作正常,可以从db读取数据到文本字段,但是当我将数据放入文本字​​段时,出现错误。

public static void setData()
{
    try
    {
        String query2 = "INSERT INTO info(name,dob,age,email,address) VALUES"+
    "("+name+","+dob+","+age+","+email+","+address+")";

        statement.executeUpdate(query2);
    }catch(Exception ex)
    {
        System.out.println(ex);
    }
}

the view class has the addBtn button that tries to set the data to the db. 视图类具有试图将数据设置为db的addBtn按钮。

public void actionPerformed(ActionEvent e)
{
    conn.name = nameBox.getText();
    conn.dob = nameBox.getText();
    conn.age = ageBox.getText();
    conn.dob = dobBox.getText();
    conn.email = email.getText();

    conn.setData();
    System.out.println(nameBox.getText()+" "+ dobBox.getText()+" "+
    ageBox.getText()+" "+ email.getText()+" "+addrBox.getText());
}

this error pops up: 出现此错误:

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; java.sql.SQLSyntaxErrorException:您的SQL语法有错误; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'taylor,01-03-04,14,jt@gmail.com,123 harris blvd)' at line 1 在第1行的'taylor,01-03-04,14,jt @ gmail.com,123 harris blvd)'附近检查与您的MariaDB服务器版本相对应的手册以使用正确的语法

You should have your name quoted "('"+name+"' (there is single quotation mark there ' ). The same will apply for any other string type values - email and address. 你应该把你的名字报"('"+name+"' (有单引号出现' )这同样适用于任何其他。 string类型的值-电子邮件和地址。

Besides, I would rather use prepared statements for that, so quotations etc will be done for you. 此外,我宁愿为此使用准备好的语句,因此将为您完成报价等。

MariaDB insert example: MariaDB插入示例:

INSERT INTO person (first_name, last_name) VALUES ('John', 'Doe'); INSERT INTO person(first_name,last_name)VALUES('John','Doe');

In your case (JDBC) Change to use bind variables : 在您的情况下(JDBC)更改为使用绑定变量

try {
    String query2 = "INSERT INTO info(name,dob,age,email,address) VALUES(?,?,?,?,?)";
    statement.setString(1, name);        
    statement.setString(2, dob);        
    statement.setString(3, age);        
    statement.setString(4, email);        
    statement.setString(4, address);        
    statement.executeUpdate(query2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM