[英]Is there anyway to insert data to table with 2 different foreign keys from 2 different tables?
I have trouble when inserting data from jsp to database. 将数据从jsp插入数据库时遇到麻烦。 I have 3 tables:
我有3张桌子:
Books(bookid), Users(id), Review(b_id,u_id) , foreign key b_id, u_id references to 2 table above. Books(bookid),Users(id),Review(b_id,u_id),外键b_id,u_id引用了上面的2个表。 Here is my code so far:
到目前为止,这是我的代码:
java java的
public void insert(ReviewModel model) {
try {
String b_id = null;
String u_id = null;
String sql = "insert into review (content,datePost,rating,b_id,u_id)\n"
+ "values (?,?,?,(select BookID from Books where BookID = '" + b_id + "'),(select id from Users where id = '" + u_id + "') )";
PreparedStatement statement = connection.prepareCall(sql);
statement.setString(1, model.getContent());
statement.setDate(2, (Date) (model.getDatePost()));
statement.setFloat(3, model.getRating());
statement.setInt(4, model.getBookid());
statement.setInt(5, model.getUserid());
statement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(ReviewDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
The problem lies here: 问题出在这里:
"...where BookID = '" + b_id + "')..."
statement.setInt(4, model.getBookid());
statement.setInt(5, model.getUserid());
The number of set parameters and the question marks must match. 设置参数的数量和问号必须匹配。 You try to bind it as a named parameter, however in your sql you just concat a null string to it.
您尝试将其绑定为命名参数,但是在sql中,您仅将空字符串连接到该参数。 So either remove the parameter setter lines above and fill up the string variables like
因此,要么删除上面的参数设置器行,然后填充字符串变量,例如
String b_id=mode.getBookId()
or use placeholder of '?' 或使用占位符“?” :
... where BookID = ? ...
:
... where BookID = ? ...
... where BookID = ? ...
(use the latter one, the first one is vulnerable to sql injection) (使用后一个,第一个容易受到sql注入的攻击)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.