如何在预准备语句中添加此值作为查询?

时间:2013-04-22 06:03:34

标签: mysql jdbc prepared-statement

Public void aMethod(String itemName, String theUsersName){  

preparedStatement = conn.prepareStatement("INSERT INTO items  (Owner_ID, Name, State)               VALUES         (?,?,?) ");
preparedStatement.setString(1, "(SELECT id FROM users WHERE username     = ' "+theUsersName+"')");
preparedStatement.setString(2, itemName); 
preparedStatement.setString(3, state);
preparedStatement.executeUpdate();

}

用户名表包含用户名和ID 这里我给了theUsersName并希望找到该用户名的id,设置Item表中新项目的Owner_ID = theUsername的id。

4 个答案:

答案 0 :(得分:3)

如果它没有抛出异常,请试一试(或者我将删除此

String query =  "INSERT INTO items  (Owner_ID, Name, State) " +
                "SELECT ID, ? AS Name, ? AS State " +
                "FROM   users " +
                "WHERE  userName = ? " 
preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1, itemName);
preparedStatement.setString(2, state); 
preparedStatement.setString(3, theUsersName);
preparedStatement.executeUpdate();

答案 1 :(得分:1)

将其插入原始INSERT语句中:

INSERT INTO items (Owner_ID, Name, State)
VALUES (SELECT id FROM users WHERE username = ?, ?,?)

并将第一个参数替换为实际值:

preparedStatement.setString(1, theUsersName);

答案 2 :(得分:1)

你可以这样做:使用INSERT INTO SELECT..

INSERT INTO items  (Owner_ID, Name, State)
SELECT id,?,? FROM users WHERE 
username = ?

或使用这样的子查询:

INSERT INTO items (Owner_ID, Name, State)
VALUES ((SELECT id FROM users WHERE username = ? LIMIT 1),?,?)

您必须将限制设置为1.

答案 3 :(得分:1)

您首先必须从users表中获取Id,然后您可以传递它。看看:

preparedStatement = conn.prepareStatement("SELECT id FROM users WHERE username = ' "+theUsersName+"'");
ResultSet rs=preparedStatement.executeQuery();
 if(rs.next())
int id=rs.getInt(1);
preparedStatement.setString(1,id);