jdbc
1. 第一步添加jar包 并 add library
2. 加载驱动 Class.forname("com.mysql.cj.jdbc.Driver");
3. 获取连接对象 Connection connection=DriverMannger。getCollecttion(url,user,password);
4. 获取执行sql语句的对象 : Statement statement=connection.createStatement()
5. 执行sql语句 int row=statement.executeUpdate(sql) 或 ResultSet resultset=
statement.executeQuery(sql);然后遍历结果
6. 关闭资源
1. 如何防止被sql注入
1.什么是sql注入 ---> sql拼接安全问题
statement存在sql注入问题 : 因为踏的sql字符串拼接
解决方案 : 使用PrepareStatement来进行sql的预编译
2. 正式开发时的模式
每一张表 ----> dao类[操作该表] 和 实体类(与表结构一样)
tb_user ---->UserDao 和 User
3.抽取到DaseDao中
写一个BaseDao作为父类,提高代码重用性
static 加载驱动
获取链接
-
在src根目录文件下创建一个属性文件 db.propertis
# = 后不能加双引号
username=root
password=123@qwr
url= jdbc:mysql://localhost:3306/aaa?serverTimezone=Asia/Shanghai
driverName=com.mysql.cj.jdbc.Driver
-
读取属性文件中的内容
// 写静态属性,在静态代码块中为其赋值
private static String url;
private static String username;
private static String password;
private static String drivername;
static{
try{
InputStream resourceAsStream = BaseDao.class.ResourceAsStream("/db.properties");
Properties properties =new Properties();
properties.load(resourceAsStream)
drivername = properties.get("drivername");// 要和属性文件里的key对应
url = properties.get("url");// 要和属性文件里的key对应
name = properties.get("name");// 要和属性文件里的key对应
password = properties.get("password");// 要和属性文件里的key对应
Class.forName(drivername);
}catch(Execption e){
e.printStackTrace;
}
}
(3)BaseDao 增删改抽取
// 抽取增删改公共方法
public int update(String sql,Object... params){
try{
getConnection();
ps = connection.perpareStatement(sql)
for(int index=0;index<params.length;index++){
ps.setObject(index+1,params[index])
}
int i = ps.executeUpdate();
return i;
}catch(Exception e){
e.printStackTrace;
}finally{
closeAll();
}
return 0;
}

浙公网安备 33010602011771号