我有一个名为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);
     }
    }


“读取”是文件中的值。我想将这些值插入到数据库中的表中,该表的参数(名称,年龄,身高,体重)为每行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();行创建了与数据库的连接,该数据库具有另一个我在这里没有写的方法。我认为问题出在我的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

10-05 20:50
查看更多