使用 JDBC 在 MySQL 中插入 select

Posted

技术标签:

【中文标题】使用 JDBC 在 MySQL 中插入 select【英文标题】:insert in select in MySQL with JDBC 【发布时间】:2014-01-04 15:40:04 【问题描述】:

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

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

此代码无效。如何更正?

【问题讨论】:

无效怎么办?顺便说一句:您几乎不需要转换为ConnectionPreparedStatement,因为方法已经返回了那些(来自包java.sql),这可能表明您对变量使用了错误的类型。 【参考方案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 = ?

    inserting 带有select 时,您不需要VALUES 关键字。 您使用了错误的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 )

参考:

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

【讨论】:

我收到一个错误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

以上是关于使用 JDBC 在 MySQL 中插入 select的主要内容,如果未能解决你的问题,请参考以下文章