Reputation: 35
I want to read data from a txt file and insert it into my database, but my code only insert 16 lines and stops. The txt file has 200 lines. I don't know what I'm doing wrong. Any help will be appreciated. Thanks in advance
Here is my 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 INTO 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();
}
}
Upvotes: 2
Views: 32503
Reputation: 91
You code looks like workable, not the best way but should work.
You are not doing any kind of validation on the file and my guess is that there is a problem with the file. I can not have sure because you did not sent the file.
Some suggestions:
Create a connection class, so you do not need you database user, password, etc... every time you need to do something database related.
Connection pool are also great.
Cheers !!!
//update with example:
//create a class that will open your connection and do other sql stuff for you
//so you busineess rules will be more readable
SQLHelper sqlHelper = new SQLHelper();
sqlHelper.startCON();
String line = null;
while((line=br.readLine()) != null){
String[] tmp=line.split(",");
//I will check here the size of the line readed, I do not know how is a common size so I am using 10 chars,
//change it as your needs, you also need to validate is the split worked and found your 4 fields
if(line.length()>9 && tmp.length==4)
{
sqlHelper.toResultat(tmp);
}
Upvotes: 0
Reputation: 2110
First problem was the line 17 containing nothing
Now for the second one (managing empty lines) :
while((line=br.readLine())){
//Make sure the line is not null, not empty, and 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];
// do the sql query
} else {
// manage where the line doesn't fit the pattern
}
Upvotes: 1