我的文本文件如下:
george 19 180 75
paul 20 182 84
laura 21 176 73
... ... ... ...
在我的程序中,我读取了这个文件并将其内容添加到我的数据库中的一个表中,该表具有参数(名称,年龄,身高,体重)。代码看起来像
public static void main(String[] args) throws IOException, SQLException {
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];
addpatient(connection, preparedstatement, name, age, height, weight);
}
}
catch (IOException e) {System.out.println("There was a problem: " + e);}
if (connection != null)
try{connection.close();} catch(SQLException ignore){}
}
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();
}
当我运行此代码时,这会将george,paul添加到name列等。 但我的问题是当我在我的文件中添加一个新条目时:
Rachel 20 175 78
再次运行程序,它再次将所有值添加到我的数据库中,但我只想添加最新的条目。我怎样才能做到这一点。有什么像追加?谢谢你的帮助!
答案 0 :(得分:0)
首先,在你的代码编写语句中没有任何意义。表示每次调用addpatient
方法时都会创建预准备语句。除此之外你可以这样做:
In your main method :
{
preparedstatement=connection.prepareStatement("insert into allpatients(name, age, height, weight) values(?,?,?,?)");
//Your rest code comes here
addPatient(preparedstatement,name,age,height,weight);
}
public static void addPatient(PreparedStatment preparedstatement, String name, String age, String height, String weight ){
preparedstatement.setString(1, name);
preparedstatement.setString(2, age);
preparedstatement.setString(3, height);
preparedstatement.setString(4, weight);
preparedstatement.executeUpdate();
}
每次执行addPatient方法时,它都只在当前表中添加记录。
答案 1 :(得分:-1)
我建议如果你有很多数据要存储,你可以在PreparedStatement中使用addBatch()方法。