[英]insert in select in MySQL with JDBC
我想將一行中的值插入到另一行中,這是我的代碼:
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
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 = ?
select
inserting
時不需要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 )
參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.