简体   繁体   English

我使用JDBC更新数据,但是它不起作用

[英]I use JDBC to update the data but it doesn't work

I try to use JDBC to insert and update the data. 我尝试使用JDBC插入和更新数据。 The insert function works well, but the update function didn't change anything in the database. 插入功能运行良好,但更新功能未更改数据库中的任何内容。 There is no exception while running it. 运行它时也不例外。

I'm sure the RoomID exists and it is correct. 我确定RoomID存在并且正确。

This is my insert function,this works 这是我的插入功能,有效

private static Connection conn;
private PreparedStatement pres;

public void saveRoom(Room room) {
    String sql = "insert into ROOM(roomid, object) values(?,?)";
    try {
        pres = conn.prepareStatement(sql);
        pres.setObject(1, room.getRoomId());
        pres.setObject(2, roomToBlob(room));
        pres.addBatch();
        pres.executeBatch();
        conn.commit();
        if (pres != null) {
            pres.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

This is my update function, this doesn't work. 这是我的更新功能,不起作用。 There is no exception but the data doesn't change. 也不例外,但数据不会更改。

private static Connection conn;
private PreparedStatement pres;

public void updateRoom(ArrayList<Room> RoomList) {
    String sql = "update ROOM set room.object= ? where room.roomid like ?";
    try {
        pres = conn.prepareStatement(sql);
        for (int i = 0; i < RoomList.size(); i++) {
            pres.setObject(1, roomToBlob(RoomList.get(i)));
            pres.setObject(2, RoomList.get(i).getRoomId());
            pres.addBatch();
        }
        pres.executeBatch();
        conn.commit();
        if (pres != null) {
            pres.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

I find the problem and solve it, but i still doesn't know why that happen. 我找到了问题并解决了,但我仍然不知道为什么会这样。 My solution is: 我的解决方案是:

Class A has a Arraylist list public void update(){database.updateRoom(list);} 类A具有一个Arraylist列表public void update(){database.updateRoom(list);}

Class B : A a = new A(); B类:A a = new A(); database.updateRoom(a.getList()); database.updateRoom(a.getList()); This has no excepetion, but no data change in the database. 这没有例外,但数据库中没有数据更改。

a.update(); a.update(); this works well, the data change correctly. 这很好,数据正确更改。

Why this happens? 为什么会这样?

As suggested in comments, you need to change the UPDATE statement: 如注释中所建议,您需要更改UPDATE语句:

String sql = "update ROOM set room.object= ? where room.roomid = ?";

The LIKE value expression is used for matching parts of strings. LIKE value表达式用于匹配部分字符串。 For example you use LIKE 'ma%' when you want for find all the strings that begin with the letters ma (such as mat , man , map ). 例如,当您要查找以字母ma开头的所有字符串(例如matmanmap )时,可以使用LIKE 'ma%'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM