0

我有一个文本文件,如下所示:

    george   19   180     75
    paul     20   182     84
    laura    21   176     73
    ...      ...  ...     ...

我想读取这个文件并将其内容添加到我的数据库中带有参数(姓名、年龄、身高、体重)的表中。名字乔治,保罗,劳拉应该添加到名字等。我写了这样的代码。

    public static void main(String[] args) throws IOException {

    PreparedStatement preparedstatement = null;

    try{
        String read=null;
        in = new BufferedReader(new FileReader("patientlist.txt")); 
        while ((read = in.readLine()) != null) {
            String[] splited = read.split("\\s+");
            name=splited[0];
            age=splited[1];
            height=splited[2];
            weight=splited[3];       
        }
        try {
            addpatient(connection, preparedstatement, name, age, height, weight);   
            if (connection != null)
            try{connection.close();} catch(SQLException ignore){}
            }
        catch (SQLException error) {System.out.println(error);} 
    }

    catch (IOException e) {System.out.println("There was a problem: " + e);}        
    }

    public static void addpatient(Connection connection, PreparedStatement preparedstatement, String name, String age2, String height2, String weight2) throws SQLException{
    preparedstatement=connection.prepareStatement("insert into allpatients(name, age, height, weight) values(?,?,?,?)");
    preparedstatement.setString(1, name);
    preparedstatement.setString(2, age);
    preparedstatement.setString(3, height);
    preparedstatement.setString(4, weight);
    preparedstatement.executeUpdate();

}

我认为问题出在我的 while 循环上,也许我必须添加一个我无法做到的 for 循环,我不是一个很好的程序员,我很感激帮助。谢谢!

4

2 回答 2

1
while ((read = in.readLine()) != null) {
            String[] splited = read.split("\\s+");
            name=splited[0];
            age=splited[1];
            height=splited[2];
            weight=splited[3];   
            addpatient(connection, preparedstatement, name, age, height, weight);   
         }

if (connection != null)
            try{connection.close();} catch(SQLException ignore){}
            }

addpatient()while 循环放在里面,然后只有它会调用。

于 2013-09-10T11:28:04.883 回答
0

你这样做是不对的。您需要做的是将值添加到循环中的preparedstatement,然后在循环外执行语句

preparedstatement = //Initialize
while(condition){
   preparedstatement.setString(1, name);
   preparedstatement.setString(2, age);
   preparedstatement.setString(3, height);
   preparedstatement.setString(4, weight);
   preparedstatement.addBatch();
}
preparedstatement.executeBatch();
于 2013-09-10T11:31:23.107 回答