有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在嵌套的sql语句java中连接动态值

我试着寻找有关它的信息,但似乎没有关于它的例子
我有这样一句话:

long userID = user.getId();
String query = "select userclient.username from twitter_content.userclient where userclient.userid = " +
            "(select follower.followerid from twitter_content.follower where follower.followerid = userclient.userid and follower.userid = "+userID+")";

但是Eclipse将“userID”读取为字符串,而不是变量。如何使Eclipse将“userID”作为变量读取


共 (1) 个答案

  1. # 1 楼答案

    最佳实践是使用PreparedStatement和占位符?的输入参数

    用法示例(来自JavaDocs):

    PreparedStatement stmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?");
    stmt.setBigDecimal(1, 153833.00)
    stmt.setInt(2, 110592)
    

    将这个例子应用到你的案例中,你会得到如下结果:

    // prepare connection "conn" earlier
    long userID = user.getId();
    PreparedStatement stmt = conn.prepareStatement("select userclient.username from twitter_content.userclient where userclient.userid = (select follower.followerid from twitter_content.follower where follower.followerid = userclient.userid and follower.userid = ?)");
    stmt.setLong(1, userID);