insert in select in MySQL with JDBC

不想你离开。 提交于 2021-02-17 06:54:05

问题


I would like to have a value from a row inserted into an other row here is my code:

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
}

This code is not valid. How do I correct it?


回答1:


I get an error 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

It was due to error in SELECT .. statement.
Modified statement is:

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

  1. You don't require VALUES key word when inserting with a select.
  2. You used a wrong DATEADD function syntax. Correct syntax is Date_add( date_expr_or_col, INTERVAL number unit_on_interval).

You can try your insert statement as corrected below:

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

Refer to:

  1. INSERT ... SELECT Syntax
  2. DATE_ADD(date,INTERVAL expr unit)


来源:https://stackoverflow.com/questions/20922966/insert-in-select-in-mysql-with-jdbc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!