Using transaction with JSP

I am using JConnector of MYSQL 5.0 to connect the database.

Following are the codes of two insert statements.

public int insert(){

try{

Class.forName("com.mysql.jdbc.Driver");

Connection conn =

DriverManager.getConnection("jdbc:mysql://localhost/db?" +

"user=myname&password=12345");

String sSQL = "INSERT INTO tbl";

sSQL += "(fielda,fieldb)";

sSQL += " VALUES (?,?)";

prepStat = conn.prepareStatement(sSQL);

prepStat.setString(1,"a");

prepStat.setLong(2,"b");

prepStat.executeUpdate();

String sSQL = "INSERT INTO tblB";

sSQL += "(fielda,fieldb)";

sSQL += " VALUES (?,?)";

prepStat = conn.prepareStatement(sSQL);

prepStat.setString(1,"c");

prepStat.setLong(2,"d");

prepStat.executeUpdate();

String sSQL ="SELECT MAX(tblid) FROM tblB";

prepStat = conn.prepareStatement(sSQL);

rs=prepStat.executeQuery();

rs.next();

maxId= rs.getLong(1);

return maxId;

}

What I want to do is,

1)The transaction will be rollback if any one of the operation failed;

2)In tblB, there is a field called "tblid", which is an autoincrement field. I want return the value of "tblid" of the newly inserted field to the user if operation succeeded, or return -1 if operation failed.

But how to do this?

[1378 byte] By [william108a] at [2007-11-27 6:33:31]
# 1

1.) On your connection instance, call setAutoCommit(false)

2.) Move the connection declaration out of the try block, add a catch block for rolling back and a finally block for closing the connection

3.) Use StringBuffer or StringBuilder for concatenating Strings; it's more efficient than sequential += operations on String

4.) Try to move the DB connection stuff out of your JSP and put it into classes

5.) For autoincrement values, here's an article:

http://dev.mysql.com/tech-resources/articles/autoincrement-with-connectorj.html

quittea at 2007-7-12 17:59:25 > top of Java-index,Java Essentials,Java Programming...