import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.PreparedStatement;
public class testcommit
{
/**
* @param args
* @throws SQLException
*/
public static void main(String[] args) throws SQLException
{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
Connection connection = null;
// Statement statement=null;
// String sql="";
try
{
connection = dataSource.getConnection();
// statement=connection.createStatement();
connection.setAutoCommit(false);
// sql="insert into t1(a,b)values('345','gdf')";
// statement.executeUpdate(sql);
// sql="insert into t2(c,d)values('43243','dddddddd')";
// statement.executeUpdate(sql);
// System.out.println(statement.executeBatch());
if (zhuanchu("aaa", 10.00, connection) == 0)
throw new SQLException("转出操作失败");
if (zhuanru("bbb", 10.00, connection) == 0)
throw new SQLException("转入操作失败");
connection.commit();
connection.setAutoCommit(true);
connection.close();
System.out.println("转账操作成功!");
} catch (SQLException e)
{
connection.rollback();
connection.setAutoCommit(true);
connection.close();
e.printStackTrace();
System.out.println(e);
}
}
public static int zhuanchu(String zhanghao, double jine, Connection conn)
{
int rtnVal = 1;
PreparedStatement pStatement = null;
ResultSet rs = null;
try
{
pStatement = conn.prepareStatement("select yue from t1 where yonghuming=?");
pStatement.setString(1, zhanghao);
rs = pStatement.executeQuery();
if (rs.next())
{
if (rs.getDouble("yue") - jine < 0)
{
System.out.println(zhanghao + "的余额不足");
rtnVal = 0;
} else
{
pStatement = conn.prepareStatement("update t1 set yue=yue-? where yonghuming=?");
pStatement.setDouble(1, jine);
pStatement.setString(2, zhanghao);
if (pStatement.executeUpdate() == 0)
rtnVal = 0;
}
} else
{
rtnVal = 0;
}
pStatement.close();
} catch (Exception e)
{
System.out.println(e);
rtnVal = 0;
}
return rtnVal;
}
public static int zhuanru(String zhanghao, double jine, Connection conn)
{
int rtnVal = 1;
PreparedStatement pStatement = null;
try
{
pStatement = conn.prepareStatement("update t1 set yue=yue+? where yonghuming=?");
pStatement.setDouble(1, jine);
pStatement.setString(2, zhanghao);
if (pStatement.executeUpdate() == 0)
rtnVal = 0;
pStatement.close();
} catch (Exception e)
{
System.out.println(e);
rtnVal = 0;
}
return rtnVal;
}
}
