insert-in-select-in-mysql和jdbc

vatpfxk5  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(286)

我想把一行中的一个值插入另一行,这是我的代码:

static void addVipMonth(String name) throws SQLException
{
    Connection conn = (Connection) DriverManager.getConnection(url, user, pass);
    PreparedStatement queryStatement = (PreparedStatement) conn.prepareStatement("INSERT INTO vips(memberId, gotten, expires) " +
            "VALUES (SELECT name FROM members WHERE id = ?, NOW(), DATEADD(month, 1, NOW()))"); //Put your query in the quotes
    queryStatement.setString(1, name);
    queryStatement.executeUpdate(); //Executes the query
    queryStatement.close(); //Closes the query
    conn.close(); //Closes the connection
}

此代码无效。我该怎么纠正呢?

uoifb46i

uoifb46i1#

我出错了 17:28:46 [SEVERE] com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MyS QL server version for the right syntax to use near ' NOW(), DATE_ADD( now(), INT ERVAL 1 MONTH )' at line 1 –桑奇克斯
这是由于错误的 SELECT .. 声明。
修改后的语句是:

INSERT INTO vips( memberId, gotten, expires )  
   SELECT name, NOW(), DATE_ADD( now(), INTERVAL 1 MONTH )
    FROM members WHERE id = ?

你不需要 VALUES 关键词什么时候 inserting 用一个 select .
你用错了 DATEADD 函数语法。正确的语法是 Date_add( date_expr_or_col, INTERVAL number unit_on_interval) .
您可以尝试下面更正的insert语句:

INSERT INTO vips( memberId, gotten, expires )  
   SELECT name FROM members
     WHERE id = ?, NOW(), DATE_ADD( now(), INTERVAL 1 MONTH )

请参阅:
插入。。。选择语法
添加日期(日期,间隔表达式单位)

相关问题