事务:
为什么要开启事务,在程序中并不是编译过了就行了,逻辑行的同才行。
有了事务可以更好的帮我们执行逻辑
数据源:
数据库连接优化 帮我们更快的链接数据库
数据源有个数据库池用的话直接从数据库池中拿就行
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
public class T1 {
/**
* 常见connection对象
*/
private static T1 ourInstance = new T1();
private DataSource dataSource = null;//申请一个数据源 接口为空
public static T1 getInstance() {
return ourInstance;
}
private T1() {//因为这里是构造器 只要创建对象就会先调用构造器
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
try {
comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
comboPooledDataSource.setJdbcUrl("jdbc:mysql://47.101.201.210/Test?useSSL=FALSE&serverTimezone=UTC");
comboPooledDataSource.setUser("root");
comboPooledDataSource.setPassword("Sb1996350.");
comboPooledDataSource.setMaxPoolSize(3);//最大连接数
comboPooledDataSource.setMinPoolSize(1);//最小连接数
dataSource = comboPooledDataSource;
Connection connection = dataSource.getConnection();//这里需要dataSource中的getConnection这个方法来返回连接对象
} catch (Exception e) {
e.printStackTrace();
}
}
public Connection getdataSource() throws Exception {
return dataSource.getConnection();
}
public static void main(String[] args) throws Exception {
Connection connection = new T1().getdataSource();
connection.setAutoCommit(false);//开启事务 为什么要开启事务 因为在代码中不是编译过了就算成功了,逻辑过了才算成功
connection.commit();//提交事务
//开启事务还有一个好处,事务有排它锁,当你修改数据时能保证数据的唯一型
connection.close();
}
}
了,里面是加载好的数据库连接