您的位置:首页 > 其它

JDBC的事物管理

2012-11-03 10:21 316 查看
package jdbc;

import java.io.FileInputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Properties;

public class JdcbManager {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

Properties jdbcProperty=new Properties();

try{

jdbcProperty.load(new FileInputStream("D:/tec_workspace/Cache/src/jdbc.properties"));

}catch(Exception e)

{

e.printStackTrace();

}

String driver=jdbcProperty.getProperty("jdbc.driver");

String url=jdbcProperty.getProperty("jdbc.url");

String username=jdbcProperty.getProperty("jdbc.username");

String pwd=jdbcProperty.getProperty("jdbc.password");

Connection conn = null;

Statement stmt=null;

try {

Class.forName(driver);

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

conn=DriverManager.getConnection(url,username,pwd);

conn.setAutoCommit(false);

stmt=conn.createStatement();

String psql="insert into t_order (ID,Amount,clientname) values(?,?,?)";

/*PreparedStatement pstmt = conn.prepareStatement(psql);

pstmt.setInt(1, 1);

pstmt.setInt(2, 1);

pstmt.setString(3, "helloword");

pstmt.executeUpdate();

*/

String sql="insert into t_order (ID,Amount,clientname) values(8,4,'helloword')";

stmt.executeUpdate(sql);

System.out.print("Transaction Roll Back");

conn.commit();

//conn.rollback();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

finally{

if(stmt!=null){

try {

stmt.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if(conn !=null){

/*try {

//conn.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}*/

}

}

}

}

1.当 conn.setAutoCommit(false)的时候,如果conn.close(); 连接关闭的时候,会自动提交数据

2.如果连接不关闭的话,则数据不会提交
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: