从txt文件中读取数据并使用java将其插入数据库 [英] Read data from txt file and insert it into database using java
本文介绍了从txt文件中读取数据并使用java将其插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从txt文件中读取数据并将其插入到我的数据库中,但我的代码只插入16行并停止。 txt文件有200行。
我不知道我做错了什么。
任何帮助将不胜感激。提前致谢
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
这是我的代码:
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();
}
}
推荐答案
首先问题是第17行什么都没有
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
}
这篇关于从txt文件中读取数据并使用java将其插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文