简体   繁体   中英

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

I try to use JDBC to insert and update the data. 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.

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

Class B : A a = new A(); database.updateRoom(a.getList()); This has no excepetion, but no data change in the database.

a.update(); this works well, the data change correctly.

Why this happens?

As suggested in comments, you need to change the UPDATE statement:

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

The LIKE value expression is used for matching parts of strings. 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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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