简体   繁体   English

使用 JDBC 在 MySQL 中插入选择

[英]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 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 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.这是由于SELECT ..语句中的错误。
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 .使用select inserting时不需要VALUES关键字。
  2. You used a wrong DATEADD function syntax.您使用了错误的DATEADD函数语法。 Correct syntax is Date_add( date_expr_or_col, INTERVAL number unit_on_interval) .正确的语法是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 INSERT ... SELECT 语法
  2. DATE_ADD(date,INTERVAL expr unit) DATE_ADD(日期,INTERVAL expr 单位)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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