jdbc笔记:
第一步:引包 导入java连接数据库的jar包
第二步:获得驱动 Class.forName("com.mysql.jdbc.Driver");
第三步:获得连接 Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名","用户名","密码");
第四步: 加载通道: 状态通道:Statement st=conn.createStatement();
预状态通道: PreparedStatement ps=conn.PreparedStatement();防止sql注入,提高代码的可读性,以可维护性;
第五步:sql语句(主要看选择什么通道)
第六步:执行sql语句; 预状态通道需要绑定"?";
增删改使用 executeUpdate()
查询语句使用:executeQuary()----->返回结果集 ResultSet
通过while循环遍历 ResultSet
第七部: 关闭资源 Connection,Statement,PreparedStatement,ResultSet都需要关闭
Dao模式 (接口,放一些增删改查的方法体)
Dao的实现类,重写Dao层的方法
还要有与数据库表一一对应的实体类
数据库中,有一张Person表,字段 id,name,age,birthday
使用java代码操作数据库表,需要创建一个与Person表对应的实体类
实体类
public class Person {
private int id;
private String name;
private int age;
private Date birthday;
写构造方法
写getter和setter的方法
}
Dao层
public interface PersonDao{
可以写增删改查的方法
例如:查询数据库表中所有的Person
public List<Person> getAll();
}
Dao层的实现类
public class PersonDaoImpl implement PersonDao{
@Override
public List<Person> getAll(){
获得驱动
获得连接
sql语句
执行sql
return null;
}
}
测试类
public class TestPerson{
PersonDao pd=new PersonDaoImpl();
List<Person> list=pd.getAll();
...
}
Sql注入
在使用状态通道时,写一个使sql语句恒等的关系语句,直接进入到系统内
封装JDBC
//封装驱动
static{
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){
e.printStackTrace();
}
}
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
//获得连接
public Connection getConnection(){
try{
conn=DriverManager.getConnection();
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
//封装增删改
public boolean doSql(String sql,List<Object> params ){
boolean flag=false;
conn=this.getConnection();
ps=conn.createPreparedStement();
for(int i=0;i<params.size();i++){
ps.setObject(i+1,params.get(i));
}
int e=ps.executeUpdate();
if(e>0){
flag=true;
}
//封装查询语句
public ResultSet doSql(String sql,List<Object> params ){
boolean flag=false;
conn=this.getConnection();
ps=conn.createPreparedStement();
for(int i=0;i<params.size();i++){
ps.setObject(i+1,params.get(i));
}
ResultSet rs=ps.executeQuary();
rs.executeQuary;
return rs;
}
//关闭资源
public void closeAll(){
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
}