- JDBC(Java DataBase Connection):Java程序连接数据库的标准(关系数据库)
- MySQL \ Oracle \ SQL Server 所有的驱动包都实现了JDBC
- 应用程序--->JDBC---->加载不同驱动---->不同数据库
- JDBC四大组件:
1、加载驱动 ,创建连接
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(String url,String username,String password);
url为 : jdbc:mysql://localhost:3306/jdbc
数据源、连接池:连接池使用数据源来构造
2、创建statement对象
(1)Statement:语法层面(不能使用占位符)
(2)PreparedStatement:语法层面(运行占位符)、预编译(速度快)、防止SQL注入
3、执行SQL语句
Statement类执行SQL
SQL注入漏洞Statement,使用 prepare Statement ResultSet(预处理SQL)
PreparedStatement statement = connection.prepareStatement(sql);
Result封装查询后的结果
1)获取Statement
Statement statement = connection.createStatement();
2)拿到查询后的结果集
ResultSet resultSet = statement.executeQuery(sql);
3)遍历结果
while (resultSet.next()){
result.getXXX("列名称")
}
补充:更新操作 insert、update、delete
int executeUpdate(String sql,int autoGeneratedKeys)
返回值为执行更新sql后的影响行数
4、释放资源(连接)
connection.close();
statement.close();
resultSet.close();