简体   繁体   English

SQL仅插入某些列

[英]SQL Insert into Only Certain Columns

I have a database with 5 columns. 我有一个包含5列的数据库。 The first column is the ID which will be automatically incremented everytime a new row is added using this statement. 第一列是ID,每次使用此语句添加新行时,ID都会自动增加。

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 谢谢,-Nicster

PS: Yes, this is day 2 of my SQL adventure D: PS:是的,这是我的SQL冒险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. 您正在错误地执行SQ​​L。 When using preparedstatements, you need to do as follow: 使用preparedstatement时,您需要执行以下操作:

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

try to replace String update = "INSERT INTO help(?, ?, ?, ?) VALUES(?, ?, ?, ?)"; 尝试替换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);

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

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