jdbc 系列文章列表, 请查看目录: 《jdbc学习笔记》
1. jdbc 的只读特性
jdbc 的连接可以设置为只读连接, 只读连接只能执行查询, 不能执行增删改等操作.连接的只读特性需要数据库驱动支持, 并非所有数据库驱动都支持. mysql 是支持的, 但是oracle 是不支持的.对于支持只读特性的数据库驱动, 除了限制该连接不能进行更新操作之外, 还会对sql进行一定的优化.数据库连接的只读特性, 可以用于实现读写分离, 只读事务等操作.
# 开启只读事务的方法
connection
.setReadOnly(true);
2. 数据库连接只读特性测试
由于oracle驱动不支持数据库只读, 因此只能拿mysql 来进行测试.
2.1 测试查询
@Test
public void test_query() throws Exception
{
Connection connection
= DbConnUtil
.getConnection();
connection
.setReadOnly(true);
Statement statement
= connection
.createStatement();
ResultSet resultSet
= statement
.executeQuery("select * from t_user");
}
2.2 测试删除操作
抛出异常: java.sql.SQLException: Connection is read-only. Queries leading to data modification are not allowed.
@Test
public void test_delete() throws Exception
{
Connection connection
= DbConnUtil
.getConnection();
connection
.setReadOnly(true);
Statement statement
= connection
.createStatement();
statement
.execute("delete from t_user");
}