我遇到以下方法的问题。该方法生成有效查询,但无法插入表监视器。
方法:
public void upLoadData(String table, String[] dbCols,List<LinkedHashMap<String,String>> values){
String wq = "INSERT INTO "+table+" (";
for (int j = 0; j < dbCols.length; j++) {
wq+=dbCols[j]+",";
}
wq = wq.replaceAll(",$", ""); //Remove comma from the end of line.
wq+=") VALUES";
for (LinkedHashMap<String, String> val : values) {
wq+="(";
for (int i = 0; i < dbCols.length; i++) {
wq+="'"+val.get(dbCols[i])+"',";
}
wq = wq.replaceAll(",$","");
wq+="),";
}
wq = wq.replaceAll(",$", ";");
System.out.println(wq);
myDB.DBInsert(wq, MyDBPool.getConnections());
}
插入方法:
public void DBInsert(String query, Connection conn){
Statement stm;
try{
stm = conn.createStatement(); // conn from db connection pool
stm.executeUpdate(query);
}catch(SQLException ex){ex.getLocalizedMessage();}
}
输出结果为:
INSERT INTO monitor (id,arr_date,company,disp_size,disp_type,producer,prod_type,color,cond_cat,comments)
VALUES('H13/2:3445','2015-11-15','Valami','jó','21','Dell','T32','fekete','B','sadsadasdasd'),
('H14:/3:5567','2015-11-15','Nincs','TFT','19','HP','B32','piros','A','sadsadasd'),
('H13/8:3321','2015-11-15','CCCP','CRT','19','nincs','T24','fehér','D','sadsadsad');
Manualy(PhPMyAdmin)插入不是问题。 我使用JDBC和Hikari dbpool,XAMPP v3.2.1
任何帮助都将不胜感激。谢谢!
答案 0 :(得分:2)
您不是commit
,而不是close
Statement
(或Connection
)。您可以使用try-with-resources
close并添加commit
之类的
public void DBInsert(String query, Connection conn) {
try (Statement stm = conn.createStatement()){
stm.executeUpdate(query);
conn.commit();
} catch (SQLException ex) {
ex.getLocalizedMessage();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
此外,我强烈建议您使用PreparedStatement
和 ?
占位符(或绑定参数)来性能和安全原因而不是将您的插入内容构建为String
。
答案 1 :(得分:0)
感谢您的帮助和建议,最后我发现了问题,我的旧插入方法工作正常(但是我按照Elliott Frisch建议更新和重构),问题是我只交换了两个不同类型的列,所以PhPMyAdmin是处理错误(将0赋予不匹配值),但Java JDBC无法解析,因此请删除插入任务。
再一次,非常感谢! :)