简体   繁体   中英

insert in select in MySQL with JDBC

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?

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 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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