寶塔面板安裝紙殼CMS
阿新 • • 發佈:2021-01-08
1、jdbc.properties
user=root
password=123456
url=jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true
driverClass=com.mysql.jdbc.Driver
2、JDBCUtils(未考慮事物)
public class JdbcUtils {
/**
* 獲取一個連線
* @return
* @throws Exception
*/
public static Connection getConnection () throws Exception {
// 1.獲取配置檔案資訊
InputStream resource = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(resource);
String user = properties.getProperty("user" );
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driverClass = properties.getProperty("driverClass");
// 2. 載入驅動
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
/**
* 關閉連線
* @param connection
* @param statement
*/
public static void closeConnection(Connection connection, Statement statement) {
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
/**
* 關閉連線
* @param connection
* @param statement
*/
public static void closeConnection(Connection connection, Statement statement, ResultSet resultSet) {
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
/**
* @auther: zqq
* @date: 21/1/12 11:49
* @Description: query
* @param sql 執行的sql
* @param clazz 查詢的結果的型別
* @param args sql的引數
* @return: List<T>
*/
public static <T> List<T> query(String sql, Class<T> clazz, Object ...args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ArrayList<T> list = null;
try {
// 1.獲取一個連線
connection = getConnection();
// 2.預編譯一個sql語句,返回一個PrepareStatement物件
preparedStatement = connection.prepareStatement(sql);
// 3.填充佔位符
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i+1, args[i]);
}
// 4。執行sql,得到結果集
resultSet = preparedStatement.executeQuery();
// 5.獲取元資料
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
// 6.獲取一個類的反射例項
T t = clazz.newInstance();
list = new ArrayList();
// 7.遍歷得到每一行資料
while (resultSet.next()){
for (int i = 0; i < columnCount; i++) {
// 7.1獲取列值
Object object = resultSet.getObject(i + 1);
// 7.2獲取列別名
String columnLabel = metaData.getColumnLabel(i + 1);
// 7.3獲取屬性並設定屬性的值
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, object);
}
list.add(t);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(connection, preparedStatement, resultSet);
}
return list;
}
/**
* @auther: zqq
* @date: 21/1/12 11:52
* @Description: update 更新
* @param sql 執行的sql
* @param obj 可變引數
* @return: int 改變的條數
*/
public static int update(String sql, Object ...obj){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// 1.獲取連線
connection = getConnection();
// 2.預編譯sql,返回一個PrepareStatement例項
preparedStatement = connection.prepareStatement(sql);
// 3.填充佔位符
for (int i = 0; i < obj.length; i++) {
preparedStatement.setObject(i+1, obj[i]);
}
// 4.執行
return preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 5.關閉資源
closeConnection(connection, preparedStatement);
}
return 0;
}
}
測試使用
public class PreparedStatementTest {
@Test
public void testUpdate(){
String sql = "update `order` set order_name = ? where order_id = ?";
JdbcUtils.update(sql, "BB", "2");
}
@Test
public void testQuery(){
String sql = "select order_id orderId, order_name orderName, order_date orderDate from `order` where order_id = ?";
List<Order> query = JdbcUtils.query(sql, Order.class, 1);
System.out.println("query = " + query.toString());
}
}
3、JdbcUtils(考慮事物)
public class JdbcUtils {
/**
* 獲取一個連線
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception {
// 1.獲取配置檔案資訊
InputStream resource = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(resource);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driverClass = properties.getProperty("driverClass");
// 2. 載入驅動
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
/**
* 關閉連線
* @param connection
* @param statement
*/
public static void closeConnection(Connection connection, Statement statement) {
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
/**
* 關閉連線
* @param connection
* @param statement
*/
public static void closeConnection(Connection connection, Statement statement, ResultSet resultSet) {
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static <T> List<T> query(Connection connection, String sql, Class<T> clazz, Object ...args) {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ArrayList<T> list = null;
try {
// 2.預編譯一個sql語句,返回一個PrepareStatement物件
preparedStatement = connection.prepareStatement(sql);
// 3.填充佔位符
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i+1, args[i]);
}
// 4。執行sql,得到結果集
resultSet = preparedStatement.executeQuery();
// 5.獲取元資料
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
// 6.獲取一個類的反射例項
T t = clazz.newInstance();
list = new ArrayList();
// 7.遍歷得到每一行資料
while (resultSet.next()){
for (int i = 0; i < columnCount; i++) {
// 7.1獲取列值
Object object = resultSet.getObject(i + 1);
// 7.2獲取列別名
String columnLabel = metaData.getColumnLabel(i + 1);
// 7.3獲取屬性並設定屬性的值
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, object);
}
list.add(t);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(null, preparedStatement, resultSet);
}
return list;
}
public static int update(Connection connection, String sql, Object ...obj){
PreparedStatement preparedStatement = null;
try {
// 2.預編譯sql,返回一個PrepareStatement例項
preparedStatement = connection.prepareStatement(sql);
// 3.填充佔位符
for (int i = 0; i < obj.length; i++) {
preparedStatement.setObject(i+1, obj[i]);
}
// 4.執行
return preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 5.關閉資源
closeConnection(null, preparedStatement);
}
return 0;
}
}
事物發生:
- DDL操作一旦執行,都會自動提交。
- DML預設情況下,一旦執行,就會自動提交。(可以通過
set autocommit = false
的方式取消DML操作的自動提交。) - 預設在關閉連線時,會自動的提交資料
在之前的程式碼中 每次執行sql語句,最後都會去關閉一次連線,導致資料被提交,考慮到事務,則關閉連線操作自行關閉,例如:
public void testJDBCTransaction() {
Connection conn = null;
try {
// 1.獲取資料庫連線
conn = JdbcUtils.getConnection();
// 2.開啟事務
conn.setAutoCommit(false);
// 3.進行資料庫操作
String sql1 = "update user_table set balance = balance - 100 where user = ?";
update(conn, sql1, "AA");
// 模擬網路異常
//throw new Exception()
String sql2 = "update user_table set balance = balance + 100 where user = ?";
update(conn, sql2, "BB");
// 4.若沒有異常,則提交事務
conn.commit();
} catch (Exception e) {
e.printStackTrace();
// 5.若有異常,則回滾事務
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
try {
//6.恢復每次DML操作的自動提交功能
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
//7.關閉連線
JdbcUtils.closeConnection(conn, null, null);
}
}