package cn.yilong.guangfu.api.persistent.jdbc;
import org.springframework.boot.test.context.SpringBootTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
@SpringBootTest
public class Test {
/**
* jdbc
*
* 注册驱动
* 创建连接
* 控制事务
* 执行sql
*/
@org.junit.jupiter.api.Test
public void testJdbc() {
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/xiansun";
String username = "root";
String password = "123456";
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
String sql = "INSERT INTO t_invest_log(outer_user_id, invest_family_id, create_time) VALUES(1, 1, NOW())";
statement.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* jdbc手动控制事务
*
* 注册驱动
* 创建连接
* 控制事务
* 执行sql
*/
@org.junit.jupiter.api.Test
public void testJdbcTransaction() {
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/xiansun";
String username = "root";
String password = "123456";
connection = DriverManager.getConnection(url, username, password);
connection.setAutoCommit(false); //控制事务:手动提交 自动开启事务 start transaction
statement = connection.createStatement();
String sql = "INSERT INTO t_invest_log(outer_user_id, invest_family_id, create_time) VALUES(1, 1, NOW())";
statement.executeUpdate(sql);
connection.commit(); //提交事务
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally {
try {
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}