我有一个名为 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位于数据库等的name参数下,所以我将来可以使用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
关于java - 如何读取文件并将其内容添加到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18698384/