一、定义一个类,实现FruitDao.java接口
1、定义一个实现类FruitDaoImpl.java(用来实现接口FruitDao.java)
2、实现接口FruitDao.java
3、重写接口 FruitDao.java中的方法(鼠标放置红线处,选择Implement Methods,全选所有后点击OK)代码如下:
package com.happyStudy.fruit.dao.impl;
import com.happyStudy.fruit.dao.FruitDao;
import com.happyStudy.fruit.pojo.Fruit;
import java.util.List;
public class FruitDaoImpl implements FruitDao {
@Override
public List<Fruit> getAllFruit() {
return null;
}
@Override
public boolean addFruit(Fruit fruit) {
return false;
}
@Override
public boolean updateFruit(Fruit fruit) {
return false;
}
@Override
public Fruit getFruitByFname(String fname) {
return null;
}
@Override
public boolean deleteFruit(String fname) {
return false;
}
}
二、处理重写的方法:
1、处理查看所有的水果方法:
@Override
public List<Fruit> getAllFruit() {
ArrayList<Fruit> fruits = new ArrayList<>();
try {
//1、加载JDBC驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2、通过驱动管理器获取连接对象
String url = "jdbc:mysql://localhost:3306/fruitdb?useUnicode=yes&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "1111";
conn = DriverManager.getConnection(url, user, password);
//3、编写SQL语句
String sql = "select * from t_fruit";
//4、创建预处理命令对象
ps = conn.prepareStatement(sql);
//5、执行查询
rs = ps.executeQuery();
//6、解析获取的数据rs
while(rs.next()) {
int fid = rs.getInt(1);
String fname = rs.getString(2);
int price = rs.getInt(3);
int fcount = rs.getInt(4);
String remark = rs.getString(5);
Fruit fruit = new Fruit(fid, fname, price, fcount, remark);
boolean flag = fruits.add(fruit);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();