簡體   English   中英

SQL僅插入某些列

[英]SQL Insert into Only Certain Columns

我有一個包含5列的數據庫。 第一列是ID,每次使用此語句添加新行時,ID都會自動增加。

ALTER TABLE help MODIFY COLUMN id INT auto_increment

因此,因為這會自動遞增,所以我不想將其設置為任何值,因此我想到了此語句。 但是,它留下語法錯誤。 有什么想法嗎?

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

謝謝,-Nicster

PS:是的,這是我的SQL冒險D的第二天:

您可以參數化查詢中的 ,但不能參數化列和表的名稱。 因此,您需要編寫:

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

您正在錯誤地執行SQ​​L。 使用preparedstatement時,您需要執行以下操作:

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

嘗試替換String update = "INSERT INTO help(?, ?, ?, ?) VALUES(?, ?, ?, ?)";

 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