[英]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
– sanchixx17: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 = ?
VALUES
key word when inserting
with a select
.select
inserting
时不需要VALUES
关键字。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:参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.