如何读取文件并将其内容添加到数据库?

我有一个名为patientlist的文本文件,如下所示:

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

我想要做的是读取此文件并将行添加到mysql数据库中的表。 我写了这段代码来读取文件:

  public static void patients() throws IOException{ try { in= new BufferedReader(new FileReader(new File("patientlist.txt"))); } catch (FileNotFoundException e) {System.out.println("There was a problem: " + e);} while((read = in.readLine()) != null){ System.out.println(read); } } 

“read”是文件中的值。 我想将这些值插入到我的数据库中的表中,该数据库的参数(名称,年龄,高度,重量)是每行的4个值。 我无法找到如何在一条线上分离值。 因为我希望george,paul和laura在数据库等的名称参数下面所以我以后可以使用select吗? 谢谢您的帮助!

我写了一些这样的代码,你可以看一下吗?

  public static void main(String[] args) throws IOException { PreparedStatement preparedstatement = null; Connection connection = DBConnection(); 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]; } } catch (IOException e) {System.out.println("There was a problem: " + e);} try { addpatient(connection, preparedstatement, name, age, height, weight); if (connection != null) try{connection.close();} catch(SQLException ignore){} } catch (SQLException error) {System.out.println(error);} } public static void addpatient(Connection connection, PreparedStatement preparedstatement, String name, String age, String height, String weight) 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(); } 

连接连接= DBConnection(); line创建与数据库的连接,有另一种方法,我没有在这里写。 我认为问题在于我的while循环,我想我也应该放一个for循环,但我的编程不是很好请帮助,谢谢。

你可以做

 read.split("\\s+"); 

或者,如果您的值由tab分隔,

 read.split("\t"); 

使用此代码:

 String s = "george 19 180 75"; String[]split = s.split("\\s+"); for (int i = 0; i < split.length; i++) { System.out.println(split[i]); } 

输出是:

 george 19 180 75 

患者列表包含“患者”,因此我首先创建一个Patient类。 然后我将为文件中的所有行创建Patient实例。

 public class Patient { private String name; private int age; private int height; private int weight; public Patient(String line) { String[] values = line.split("\\s+"); name = values[0]; age = values[1]; height = values[2]; weight = values[3]; } // not shown: getters/setters for the fields } 

现在,读取行并创建对象

 List patients = new ArrayList<>(); while((line = in.readLine()) != null){ patients.add(new Patient(line)); } 

并使用患者列表将数据持久保存到数据库中。 对于每位患者,准备一份插入声明并坚持下去。