简体   繁体   中英

Unable to use prepareStatement in SQL

I have a peculiar situation where I am unable to use prepareStatement .

I am writing an update function in Java where in I need to update a set of fields for a row. My problem is I dont know how many fields are there to be updated. I determine this dynamically from a JSONArray . In such scenario how I can I use prepareStatement to formulate an SQL Query. As for prepareStatement the query is predefined and values are suppose to be added later. My non-functional sample code is here:

DB:MySQL using mysql driver jar file

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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