【问题标题】:Database how add data without overwriting?数据库如何添加数据而不覆盖?
【发布时间】:2013-09-10 12:05:50
【问题描述】:

我有一个文本文件看起来像:

    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();

    }

当我运行此代码时,这会将乔治、保罗添加到名称列等。 但我的问题是当我向我的文件添加一个新条目时:

   Rachel   20   175  78

并再次运行程序,它会将所有值再次添加到我的数据库中,但我只想添加最新条目。我怎样才能做到这一点。有没有类似追加的东西?感谢您的帮助!

【问题讨论】:

标签: java mysql database file filereader


【解决方案1】:

首先,在您的代码准备语句中没有任何意义。表示每次调用 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 方法时,它只会添加当前表中的记录。

【讨论】:

  • 不,我的意思是当我第一次运行时,它会将当前姓名和年龄等添加到数据库中。我希望他们留在数据库中。从另一个程序中,我在文件中添加了另一个条目。当我再次运行该程序时,我希望保留第一条记录并将新条目添加到我的数据库中
  • @Solijoli 检查我的答案。如果您在应用程序中创建表,那么您可能会遇到问题。
【解决方案2】:

你可以试试preparedstatement.clearBatch()方法 当你完成一个 jdbc 提交时,你应该关闭它。 连接对象有close()方法;

我建议如果你有很多数据要一次存储,你可以使用带有 PreparedStatement 的 addBatch() 方法。

【讨论】:

  • 我关闭了连接,即在我的代码中的 if 语句中。我应该把clearBatch()放在哪里,我不知道它实际上是如何工作的,但听起来它可以工作
猜你喜欢
  • 2018-07-15
  • 2021-06-30
  • 1970-01-01
  • 2022-01-01
  • 2016-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-07
相关资源
最近更新 更多