1. ResultSet
int executeUpdate(sql);
ResultSet executeQuery(sql);//封装了DQL查询语句的结果
boolean next();//游标向下移动一行,判断改行是否有数据
getXXX();
while(rs.next()){//ctrl+下箭头
Int id=getInt(columnIndex:1);
String name=getString(columnIndex:2);
Double money=getDouble(columnIndex:3);
Int id=getInt(columnIndex:id);//索引/列名
String name=getString(columnIndex:name);
Double money=getDouble(columnIndex:money);
//释放资源
rs.close();
stmt.close();
conn.close();
}
2.创建集合
List<Account> list=new ArrayList<>();//Account为自定义实体类
//存入集合
List.add(account);
System.out.println(list);
3.PreparedStatement【预防SQL注入】
//useServerPrepStmts=true开启预编译
String url="jdbc:mysql://db1?useSSL=false&useServerPrepStmts=true";
3.1SQL注入
- 通过操作输入来修改事先定义好的SQL语句,用以达到执行代码对服务器进行攻击的方法
- 预编译(将敏感字符进行转义),性能更高
- 获取preparedStatement对象
- 设置参数值
- 执行SQL
//单引号和双引号
String sql="select * from tb_user where username='"+name+"' and password='"+pswd+"';
//inject 注入 恒等式
'or'1'='1
//使用?占位符代替
String sql="select * from tb_user where username=?and password=?;
//通过connection对象获取,并传入对应的sql语句
PreparedStatement pstmt=conn.prepareStatement(sql);
//设置?的值
pstmt.setString(parameterIndex:1,name);//类型 索引 值
pstmt.setString(parameterIndex:2,pswd);
//执行SQL
executeUpdate();/executeQuery();//不需要再传递SQL
4.数据库连接池
4.1概念和好处
- 容器,负责分配、管理数据库连接
- 重复使用一个现有的数据库连接
- 避免链接遗漏
4.2 常见数据库连接池
- DBCP
- C3P0
- Druid