从txt文件中读取数据并使用java将其插入数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30170141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:15:43  来源:igfitidea点击:

Read data from txt file and insert it into database using java

java

提问by EL GHORRIM Sara

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

我想从 txt 文件中读取数据并将其插入到我的数据库中,但我的代码仅插入 16 行并停止。txt 文件有 200 行。我不知道我做错了什么。任何帮助将不胜感激。提前致谢

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();
    }
}

采纳答案by flafoux

First problem was the line 17 containing nothing

第一个问题是第 17 行不包含任何内容

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
}

回答by Igor

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);
}