我试图将我的HashMap插入Access数据库中,但我一直收到错误消息。这是我的代码:
for (Entry<String, String> entry : mapImpedanceAll.entrySet()) {
prep1 = entry.getKey().replaceAll("\\s", "_");
prep1=prep1.replace(":","");
prep1=prep1.replace("<","LessThan");
prep1=prep1.replaceAll("\\." ,"");
prep1=prep1.replaceAll("\\(s\\)" ,"");
prep1=prep1.replaceAll(",$" ,"");
prep1=prep1.replaceAll("%" ,"");
prep1=prep1.replace("-" ,"_");
prep1=prep1.replace("_" ,"");
if(dbColNames.contains(prep1)) {
try {
Statement qu = null;
qu =conn.createStatement();
String stg = "INSERT INTO Impedance2 "+prep1+" VALUES('"+entry.getValue()+"')";
qu.execute(stg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是错误:
net.ucanaccess.jdbc.UcanaccessSQLException:UCAExc :::: 3.0.4行列计数不匹配
我敢肯定这与声明有关,String stg = "INSERT INTO Impedance2 "+prep1+" VALUES('"+entry.getValue()+"')";
但我已经对其进行了尝试,但仍然会失败。
dbColNames
是现有数据库列名称的数组,因此我可以在添加HashMap之前对其进行检查
您的示例代码尝试执行以下操作:对于哈希映射中的每个条目,如果有一个表列可用,其名称等于键名,则尝试将此值插入数据库。
但是,您生成的INSERT语句不考虑表中的其他列。您将需要以下内容:
INSERT INTO table (col1, col2, col3, col4) VALUES (NULL, value, NULL, NULL)
要使此功能完全起作用(除非您为列定义了适当的默认值),您可以将哈希图值放在语句中的适当索引处,并用NULL(或适当的默认值;所有其他列填充);甚至不允许)。
如果您的哈希图将表示一个单一的数据集,则需要将所有数据组合到一个单一的INSERT语句中:
string sql = "INSERT INTO table (col1, col2, col3, col4) VALUES ("
+ hashmap.get("col1") + ", " + hashmap.get("col2") + ", "
+ hashmap.get("col3") + ", " + hashmap.get("col4") + ");";
我遗漏了检查值是否全部可用,此外,使用StringBuffer会更有效。如果您多次执行此操作,请考虑改用准备好的语句。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句