简体   繁体   中英

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. The setData methord seams to not be working and not sure why. 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.

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.

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; 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

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.

Besides, I would rather use prepared statements for that, so quotations etc will be done for you.

MariaDB insert example:

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

In your case (JDBC) Change to use bind variables :

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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