我想将一行中的值插入另一行,这是我的代码:
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 }
该代码无效。我该如何纠正?
我收到一个错误消息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
这是由于SELECT ..语句错误。 修改后的语句是:
SELECT ..
INSERT INTO vips( memberId, gotten, expires ) SELECT name, NOW(), DATE_ADD( now(), INTERVAL 1 MONTH ) FROM members WHERE id = ?
VALUES
inserting
select
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 )
参考: