Domanda

I am using Apache BasicDataSource to handle my database code - simply i just create methods to do particular tasks that access the database. An example can be seen below;

/**
 * Update a users display name
 * @param userid the user id to update for
 * @param displayName the display name to change too
 * @return true if update suceeded 
 */
public static boolean updateDisplayName(String userid, String displayName){
    Connection conn = null;
    String sql = "update UserAccount set displayname = ? where userid = ? ";

    try {
        conn = source.getConnection();
        PreparedStatement st = conn.prepareStatement(sql);
        st.setString(1,displayName);
        st.setString(2,userid);
        st.executeUpdate();
        return true;
    } catch (Exception e) {
        logger.warn("An error occured when updating the display name for " + userid, e);
    } finally{
        closeConnection(conn);
    }
    return false;
}

I have had a google around and can't seem to find any examples of how to use transactions. Please could someone advise me on how this might be done?

Thanks

È stato utile?

Soluzione

When you take the connection mark this connection as auto commit false

connection.setAutoCommit(false);

Once you succesfuly done your task commit that transaction

connection.commit();

In case of exception rollback that transaction

connection.rollback();

It is normal jdbc transaction you can go with other implementation of transaction as well .. Check this example here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top