Reputation: 3
I have a problem with following method. The method generate a valid query, but it cannot insert the table monitor.
The method:
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());
}
And the insert method:
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();}
}
The output is:
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) insert is not problem. I use JDBC, and Hikari dbpool, XAMPP v3.2.1
Any help will be appreciate. Thanks!
Upvotes: 0
Views: 1759
Reputation: 3
Thanks for the help and advise, finally I found the problem, my old insert method is work fine(but I update and refact as Elliott Frisch advised), the problem is only I swap two columns with different types,so PhPMyAdmin is handle the error(give 0 to mismatch value), but Java JDBC cannot resolve, so drop the insert task.
Once more, Thanks a lot! :)
Upvotes: 0
Reputation: 201447
You aren't commit
ing, and you aren't close
ing your Statement
(or Connection
). You could use a try-with-resources
close and add a commit
like
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();
}
}
}
Also, I strongly recommend you use a PreparedStatement
and ?
placeholder (or bind paramters) for performance and security reasons instead of building your inserts as String
.
Upvotes: 2