小编典典

使用JDBC在MySQL中插入select

sql

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

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
}

该代码无效。我该如何纠正?


阅读 195

收藏
2021-04-15

共1个答案

小编典典

我收到一个错误消息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’‘.sanchixx

这是由于SELECT ..语句错误。
修改后的语句是:

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

  1. 您不需要VALUES时关键字insertingselect
  2. 您使用了错误的DATEADD函数语法。正确的语法是Date_add( date_expr_or_col, INTERVAL number unit_on_interval)

您可以按照以下更正的方式尝试插入语句:

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

参考:

  1. INSERT … SELECT语法
  2. DATE_ADD(日期,INTERVAL表示单位)
2021-04-15