将HashMap插入任何数据库表 [英] Insert a HashMap into any database table
问题描述
我有一个具有以下定义的HashMap:
I have a HashMap with the following definition:
myMap = new HashMap<String,String>();
此映射由作为键的字段名称和作为课程值的字段值组成.我试图做一个采用HashMap和表名作为参数的方法.我的查询必须具有以下格式,因为我没有插入表中的所有列:
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 (?,?,?,?)
列数当然取决于HashMap的大小. 我如何通过遍历HashMap来实现这一点. 到目前为止,这是我使用另一种方法得出的结果,但我认为它不能正常工作:
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 += ";";
}
推荐答案
您需要自己生成带有列名和占位符的准备好的语句SQL字符串.这是一个启动示例:
You'd need to generate the prepared statement SQL string with column names and placeholders yourself. Here's a kickoff example:
StringBuilder sql = new StringBuilder("INSERT INTO ").append(tableName).append(" (");
StringBuilder placeholders = new StringBuilder();
for (Iterator<String> iter = dataMap.keySet().iterator(); iter.hasNext();) {
sql.append(iter.next());
placeholders.append("?");
if (iter.hasNext()) {
sql.append(",");
placeholders.append(",");
}
}
sql.append(") VALUES (").append(placeholders).append(")");
preparedStatement = connection.prepareStatement(sql.toString());
int i = 0;
for (String value : dataMap.values()) {
preparedStatement.setObject(i++, value);
}
int affectedRows = prepatedStatement.executeUpdate();
// ...
这还有一个优势,您可以使用Map<String, Object>
,其中Object
也可以是Number
(Integer
,Long
等),Date
,byte[]
等,至少PreparedStatement
已经具有setter方法的那些类型.
This has the additional advantage that you can use Map<String, Object>
where Object
can also be a Number
(Integer
, Long
, etc), Date
, byte[]
, and so on, at least those types for which the PreparedStatement
already has setter methods.
请记住,如果tableName
和map密钥是由最终用户控制的,那么您将遇到严重的SQL注入攻击漏洞.
Keep in mind that you've a serious SQL injection attack hole if the tableName
and map keys are controlled by the enduser.
这篇关于将HashMap插入任何数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!