简体   繁体   English

无法在SQL中使用prepareStatement

[英]Unable to use prepareStatement in SQL

I have a peculiar situation where I am unable to use prepareStatement . 我有一种特殊的情况,我无法使用prepareStatement

I am writing an update function in Java where in I need to update a set of fields for a row. 我正在用Java写一个更新函数,在其中我需要为一行更新一组字段。 My problem is I dont know how many fields are there to be updated. 我的问题是我不知道要更新多少字段。 I determine this dynamically from a JSONArray . 我从JSONArray动态确定。 In such scenario how I can I use prepareStatement to formulate an SQL Query. 在这种情况下,我该如何使用prepareStatement来制定SQL查询。 As for prepareStatement the query is predefined and values are suppose to be added later. 至于prepareStatement该查询是预定义的,并且值应在以后添加。 My non-functional sample code is here: 我的非功能性示例代码在这里:

DB:MySQL using mysql driver jar file DB:MySQL使用mysql驱动程序jar文件

public static int updateUser(String user) throws SQLException, JSONException{
    JSONObject jobj= new JSONObject(user) ;

    String pQuery= " UPDATE Presence SET "+(jobj.has("lat")?" lat =?,":",")+(jobj.has("lng")?" lng = ?,":",")+(jobj.has("description")? "description = ?,":",")+(jobj.has("gcm_id")?" gcm_id = ?,":",")+" WHERE id = ?";
    pst = con.prepareStatement(pQuery);
    pst.setDouble(1, jobj.getDouble("lat"));
    pst.setDouble(2, jobj.getDouble("lng"));
    pst.setString(3, jobj.getJSONObject("description").toString());
    pst.setString(4, jobj.get("id").toString());
    if(jobj.has("gcm_id"))

    pst.setString(5, jobj.getString("gcm_id"));
    int rs = pst.executeUpdate();
    return rs;
}

I don't understand what the problem is. 我不明白问题是什么。

Go through whatever loop you need to build the names of the fields in the string that will hold your SQL statement, another loop to give it the number of question marks that you need, then a third to fill in those values as you would for any other prepared statement. 经历需要循环的所有步骤,以构建将包含SQL语句的字符串中的字段名称,然后循环进行另一个循环,以为其提供所需的问号数量,然后再进行三分之一循环,以填充任何值其他准备好的陈述。 There's nothing magic about using a string literal for the prepared statement. 对于准备好的语句使用字符串文字没有什么神奇的。

-- -

requested code: 要求的代码:

private enum DataType { DOUBLE, STRING };

String names[] = { "lat", "lng", "description", "gcm_id" };
DataType types[] = { DOUBLE, DOUBLE, STRING, STRING };
// you could replace these parallel arrays with an array
// of objects, one per field, with name, type, and whatever else.

StringBuilder setString = new StringBuilder(" UPDATE Presence SET ");
boolean       firstNameAdded = false;

for (String name : names)
{
  if (jobj.has(name))
  {
    if (!firstNameAdded) { setString.append(","); }
    firstNameAdded = true;
    setString.append(String.format(" %s=?", name));
  }
}

setString.append(" where id = ?");

// if firstNameAdded is still false at this point, you didn't
// have anything in the json object to add

psmt = con.prepareStatement(setString.toString());
int i = 0;

while (i<names.length)
{
  if (jobj.has(name))
  {
    switch (types[i])
    {
      case DOUBLE: psmt.setDouble( i+1, jobj.getDouble(names[i]) )
        break;
      case STRING: psmt.setString( i+1, jobj.getJSONObject(names[i]).toString();
        break;
    }
  }
  i++;
}


psmt.setString( i+1, jobj.getString("gcm_id").toString();

int sqlResult = psmt.executeUpdate();

I did this with a simple text editor, so there may be syntax things, etc. This shoudl give you the idea. 我使用一个简单的文本编辑器完成了此操作,因此可能存在语法问题,等等。这应该给您带来了想法。 The primary complication is the different types, which I've represented here with an enum. 主要的复杂性是不同的类型,我在这里用枚举表示了这些类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM