import com.mysql.jdbc.Driver;
import java.sql.*;
public class JDBCTest {
public static void main (String[] args) {
//mysql驱动类
String driverClass = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://192.168.93.88:3306/mydb”;
String username = “root”;
String password = “”;
//数据库连接接口
Connection conn = null;
//执行sql语句的接口
Statement st = null;
try {
//加载驱动类到虚拟机
Class.forName ( driverClass );
//连接数据库
conn = DriverManager.getConnection (url,username,password);//url地址,username,password
//创建语句对象
st = conn.createStatement (); //功能是执行sql语句
String sql = "begin";
st.execute ( sql ); //执行语句
int count = st.executeUpdate ( sql );
//st.executeUpdate ( sql )返回执行成功后的语句记录数,进行数据库中的添删改操作
sql = "update Account set account = account - 1000 where id = 1;";
st.execute ( sql );
sql = "update Account set account = account + 1000 where id = 2;";
st.execute ( sql );
sql = "commit";
st.execute ( sql );
} catch (Exception e) {
e.printStackTrace ();
}
try {
String sql = "rollback";
st.execute ( sql );
} catch (SQLException e) {
e.printStackTrace ();
}finally {
//关闭这些对象,是为了释放资源
try {
if (st != null)
st.close ();
if (conn != null)
conn.close ();
} catch (SQLException e) {
e.printStackTrace ();
}
}
}
}