I have a HashMap with the following definition:
myMap = new HashMap<String,String>();
this map consists of the field names as keys and field values as of course values. I am trying to make a method that takes the HashMap and a table name as arguments. My query has to have the following format because I do not insert to all the columns in my table:
INSERT INTO $tableName (?,?,?,?)
VALUES (?,?,?,?)
The number of columns of course depends on the size of the HashMap. How can I achieve this through iterating through the HashMap. Here is what I have come up so far using a different approach but I do not think it will work properly:
public void insertData(HashMap<String, String> dataMap, String tableName) {
int size=dataMap.size();
String sql = "INSERT INTO " + tableName;
Iterator<Entry<String, String>> it = dataMap.entrySet().iterator();
int counter = 1;
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
sql += pairs.getKey()+"="+pairs.getValue();
if(size > counter )
sql += ", ";
counter++;
}
sql += ";";
}