【问题标题】:Java and Mysql Update all Records using ArraylistJava 和 Mysql 使用 Arraylist 更新所有记录
【发布时间】:2016-05-10 11:09:32
【问题描述】:

我试图运行程序所有更新的记录以显示在该程序上,但 mysql 没有变化。

    try 
    {
        User user = new User(null, null);
        user.setId(5);
        user.setName("spider");
        user.setPlatform("Mac"); 
        updateRecordToTable(user);

    ArrayList<User> userlists=new ArrayList<User>();

        userlists.add(new User("alish","Windows"));
        userlists.add(new User("galish","Ubundu"));
        userlists.add(new User("balish","Boss"));
    } 
    catch (SQLException e) 
    {

        System.out.println(e.getMessage());

    }

}

private static int updateRecordToTable(User user) throws SQLException 
{

    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;

    String updateTableSQL = "UPDATE NEWDB SET NAME =? , PLATFORM = ?  WHERE ID =? ";

    try 
    {
        dbConnection = getDBConnection();
        preparedStatement = dbConnection.prepareStatement(updateTableSQL);

        System.out.println("Record is updated all to NEWDB table!");

    } 

尝试修复这个程序。

【问题讨论】:

  • updateRecordToTable方法中看不到用户参数的用法?
  • 你没有给你的陈述任何真正的价值——只有查询。顺便提一句。 new User(null,null) 然后使用 setter 为 User 寻求额外的构造函数

标签: java mysql prepared-statement


【解决方案1】:

你必须使用参数。

private static int updateRecordToTable(ArrayList<User> users) throws SQLException 
{
  int i = 0;
  Connection dbConnection = null;
  PreparedStatement preparedStatement = null;

  String updateTableSQL = "UPDATE NEWDB SET NAME =? , PLATFORM = ?  WHERE ID =? ";

try 
{
    dbConnection = getDBConnection();
    for (User user : users){
       preparedStatement = dbConnection.prepareStatement(updateTableSQL);
       preparedStatement .setString(1, user.getName());
       preparedStatement .setString(2, user.getPlatform());
       preparedStatement .setInt(3, user.getId());
       preparedStatement .executeUpdate();
       i++;
    }
    dbConnection.commit();

    System.out.println(i + " Records updated!");

}

【讨论】:

  • 谢谢先生,这段代码更有帮助。但是不能更新所有记录。如何使用arraylist更新所有记录?
  • 您必须将方法的参数从单个用户更改为 ArrayList,并使用例如 for 循环来遍历 ArrayList。我将编辑我以前的答案给你一个例子。
猜你喜欢
  • 2013-03-08
  • 1970-01-01
  • 2013-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-11
  • 2018-06-02
相关资源
最近更新 更多