简体   繁体   中英

SQL Insert into Only Certain Columns

I have a database with 5 columns. The first column is the ID which will be automatically incremented everytime a new row is added using this statement.

ALTER TABLE help MODIFY COLUMN id INT auto_increment

So, because this will automatically increment I dont want to set it as anything, because of this I thought of this statement. However, it leaves a syntax error. Any ideas why?

   String update = "INSERT INTO help(" + name + ", " + area + ", " + date + ", " + message + ") VALUES(?, ?, ?, ?)";
        try {
            connection = plugin.getHikari().getConnection();
            // Inserting into the table
            statement = connection.prepareStatement(update);
            // Replace the '?' with the actual information
            statement.setString(1, name);
            statement.setString(2, area);
            statement.setString(3, date);
            statement.setString(4, message);
            statement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }

Thanks, - Nicster

PS: Yes, this is day 2 of my SQL adventure D:

You can parameterize values in a query, but not the names of columns and tables. So, you need to write:

String update = "INSERT INTO help(name, area, date, message) VALUES(?, ?, ?, ?)";
    try {
        connection = plugin.getHikari().getConnection();
        // Inserting into the table
        statement = connection.prepareStatement(update);
        // Values
        statement.setString(1, name);
        statement.setString(2, area);
        statement.setString(3, date);
        statement.setString(4, message);
        statement.execute();
    } catch (SQLException e) {
        e.printStackTrace();
    }

You are doing the SQL incorrectly. When using preparedstatements, you need to do as follow:

String update = "INSERT INTO help (column1, column2, column2, column4) VALUES(?, ?, ?, ?)";

try to replace String update = "INSERT INTO help(?, ?, ?, ?) VALUES(?, ?, ?, ?)"; with

 String update = "INSERT INTO help("name","area","date","message") VALUES(?, ?, ?, ?)";
    statement.setString(1, name);
    statement.setString(2, area);
    statement.setString(3, date);
    statement.setString(4, message);

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