SQL交易處理可以在預存程序中執行,同時也可以在Java中執行,操作很簡單,已標註紅色地區,代碼如下:
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try
{
// 串連資料庫
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("jdbc/test");
// 串連資料庫
conn = ds.getConnection();
stmt = conn.createStatement();
try
{
// 設定不自動認可
conn.setAutoCommit(false);
// 執行 sql
String sql = "insert ....";
int dbResult = stmt.executeUpdate(sql);
// sql 執行完畢,提交 sql
conn.commit();
catch (Exception e)
{
// 若異常則回寫
conn.rollback();
}
}
catch (Exception e)
{
result = -1;
e.printStackTrace();
}
finally
{
if (rs != null)
{
try
{
rs.close();
}
catch (Exception e)
{
}
}
if (stmt != null)
{
try
{
stmt.close();
}
catch (Exception e)
{
}
}
if (conn != null)
{
try
{
conn.close();
}
catch (Exception e)
{
}
}
}
討論Q群:236201801