本文介绍了使用JDBC在MySQL中插入select的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一行中的值插入另一行,这是我的代码:
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?
推荐答案
这是由于SELECT ..
语句中的错误所致.
修改后的语句是:
It was due to error in SELECT ..
statement.
Modified statement is:
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)
.
- You don't require
VALUES
key word wheninserting
with aselect
. - You used a wrong
DATEADD
function syntax. Correct syntax isDate_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 )
引用:
这篇关于使用JDBC在MySQL中插入select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!