JDBC
-
JDBC介绍
数据库驱动(Java语言对应的是一个jar包)
-
Jdbc使用步骤
-
导包
-
注册驱动 (仅仅做一次)
-
建立连接(Connection)
-
创建运行SQL的语句对象
-
运行语句
-
处理运行结果(ResultSet)
-
释放资源
其中:如果是添加、删除、更新操作可以没有处理运行结果这一步,查询可定会有这一步
-
注册驱动、建立连接
String sql = "select * from student"; PreparedStatement preparedStatement = connection.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery();
-
创建运行SQL的语句
String sql = "select * from student"; PreparedStatement preparedStatement = connection.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery();
-
运行语句、处理运行结果
while (resultSet.next()) { System.out.println(resultSet.getString("name")); }
-
释放资源
public static void closeConnection(AutoCloseable autoCloseable){ try { if (autoCloseable != null){ autoCloseable.close(); } }catch (Exception e){ e.printStackTrace(); } }
-
-
-
PreparedStatement
Statement 和 PreparedStatement 的区别:
-
Statement用于执行静态SQL语句
-
PreparedStatement 是预编译的SQL语句对象并保存在对象中
-
每次执行同一个PreparedStatement对象时,它就会被解析一次,但不会被再次编译,可以重复使用
-
能够避免SQL注入,相对安全
-
-
SQL注入
-
通过把SQL命令插入到Web表单提交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令
-
-
封装工具类
public class JdbcUtils { public static Connection getConnection(){ try { // 1.注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); // 2.建立连接 Properties properties = new Properties(); properties.load(JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties")); String url = properties.getProperty("url"); String username = properties.getProperty("username"); String password = properties.getProperty("password"); return DriverManager.getConnection(url, username, password); } catch (Exception e) { e.printStackTrace(); } return null; } public static void close(AutoCloseable autoCloseable){ try { if (autoCloseable != null) { autoCloseable.close(); } }catch (Exception e) { e.printStackTrace(); } } }
-
事务(面试题)
四大特性
-
原子性:一个事务是一个不可分割的工作单位,事务中包括的操作要么都做,要么都不做
-
一致性:事务必须是使数据库从一个一致性状态变成另一个一致性状态,一致性与原子性是密切相关的
-
隔离性:一个事务的执行不能被其他事务干扰
-
持久性:持久性也称永久性,指的是一个事务一旦修改,它对数据库的改变就应该是永久性的
-
-
连接池
-
数据库连接池负责分配、管理和释放数据库俩姐,允许重复使用
-