Read data from txt file and insert it into database using java -
i want read data txt file , insert database, code insert 16 lines , stops. txt file has 200 lines. don't know i'm doing wrong. appreciated. in advance
here code :
public static void main(string[] args) throws classnotfoundexception, sqlexception { string date; string heure; string parametre; string valeur; preparedstatement ps = null; connection con = null; resultset rs = null; try { bufferedreader br = new bufferedreader(new filereader("data_station_1.txt")); string username = "postgres"; string pwd = "elghorrim"; string connurl = "jdbc:postgresql://localhost:5432/bds_csf_auqliteeau"; con = drivermanager.getconnection(connurl, username, pwd); class.forname("org.postgresql.driver"); string line = null; while((line=br.readline()) != null){ string tmp[]=line.split(","); date=tmp[0]; heure=tmp[1]; parametre=tmp[2]; valeur=tmp[3]; system.out.println(date + "\t" + heure + "\t" +parametre+ "\t" +valeur); string sql = "insert resultat (date_resultat,valeur,code_pc,code_parametre,heure_resultat) values ('" + date + "','" + valeur + "','1','" + parametre + "','" + heure + "')"; ps = con.preparestatement(sql); ps.executeupdate(); } br.close(); con.close(); ps.close(); } catch(ioexception e){ e.printstacktrace(); } } }
first problem line 17 containing nothing
now second 1 (managing empty lines) :
while((line=br.readline())){ //make sure line not null, not empty, , contains 3 comma char if (line != null && !line.equals("") && line.matches('.*[,].*[,].*[,].*')) { string tmp[]=line.split(","); date=tmp[0]; heure=tmp[1]; parametre=tmp[2]; valeur=tmp[3]; // sql query } else { // manage line doesn't fit pattern }
Comments
Post a Comment