我有一个文本文件,如下所示:
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 循环,我不是一个很好的程序员,我很感激帮助。谢谢!