import java.sql.*;
import java.util.ResourceBundle;
public class JDBCTest01 {
public static void main(String[] args) {
// 获取属性配置文件
ResourceBundle db = ResourceBundle.getBundle("db");
String url = db.getString("url");
String user = db.getString("user");
String password = db.getString("password");
String driver = db.getString("driver");
//
Connection con = null;
Statement st = null;
ResultSet rs = null;
// 放大作用域
try {
// 注册驱动
Class.forName(driver);
// 获取连接对象
con = DriverManager.getConnection(url, user, password);//、、、alt + enter
System.out.println(con);
// 关闭十五自动提交机制
con.setAutoCommit(false);
con.commit();//提交事务
} catch (ClassNotFoundException | SQLException e) {
if (con != null) {
try {
con.rollback();
// 回滚事务 保证数据库数据安全
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
e.printStackTrace();
}finally {
// 关闭流 从小 到大
// rs ps/st /con
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(con != null){
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
import java.sql.*;
import java.util.ResourceBundle;
public class JDBCTest02 {
public static void main(String[] args) {
// 1. 获取属性配置文件
ResourceBundle db = ResourceBundle.getBundle("db");
String driver = db.getString("driver");
String user = db.getString("user");
String password = db.getString("password");
String url = db.getString("url");
// 2. 放大 数据库几个对象的 作用域
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
// 3.注册驱动
Class.forName(driver);
// 4. 获取数据库的 连接 对象
con = DriverManager.getConnection(url,user,password);
// url user password
// 5. 关闭事务 自动 提交 机制
con.setAutoCommit(false);
// 9. 获取 操作 对象
st = con.createStatement();
// 10. 写 sql
String sql = "insert into t_user values(111,'yy','12')";
// 11. 执行 sql
boolean execute = st.execute(sql);
// 6. 手段提交事务
con.commit();
} catch (ClassNotFoundException | SQLException e) {
// 7. 回滚事务
if (con != null) {
try {
con.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
e.printStackTrace();
}finally {
// 8. 关闭 连接 小 --- 大
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}