MyEclipse连接MySQL数据库并进行增删改查操作

实现要求
MyEclipse连接MySQL数据库并进行增删改查操作_第1张图片

下载MyEclipse的JDBC驱动包
链接:https://pan.baidu.com/s/17bpXqaieiiXVB9RtM6P0-g
提取码:ahgz
导入JDBC驱动包
MyEclipse连接MySQL数据库并进行增删改查操作_第2张图片
用SQLyog创建Pet数据库,并按照要求创建pet表
MyEclipse连接MySQL数据库并进行增删改查操作_第3张图片
给表中添加行和列并添加一些数据
MyEclipse连接MySQL数据库并进行增删改查操作_第4张图片
MyEclipse连接MySQL数据库并进行增删改查操作_第5张图片
实现代码
1、在MyEclipse中创建baseDao层基类

package com.offcn.day03.work;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/*
1.获取连接对象
2.通过反射加载驱动
*/
public class BaseDao {
     
	private Connection conn;
//	3305为端口号,pet为数据库名称,数据库账号和密码需要对应
	private String url = "jdbc:mysql://127.0.0.1:3305/pet?useUnicode=true&characterEncoding=utf-8";
	private String user = "root";
	private String password = "root";
	
	public Connection getConnection(){
     
		try {
     
			Class.forName("com.mysql.jdbc.Driver");
			if(conn == null){
     
				conn = DriverManager.getConnection(url, user, password);
			}
		} catch (ClassNotFoundException e) {
     
			e.printStackTrace();
		} catch (SQLException e) {
     
			e.printStackTrace();
		}
		return conn;
	}
	/*
	1.增删改,第一个参数传递是sql语句,第二个参数传递object类型数组,里面存放动态占位符
	2.获取连接
	3.得到需要执行aql语句
	4.给占位符赋值
	5.执行sql语句
	6.输出结果
	*/
	public int update(String sql,Object[] object){
     
		conn = getConnection();
		int num = -1;
		PreparedStatement ps = null;
		try {
     
			ps = conn.prepareStatement(sql);
			if(object != null && object.length > 0){
     
				for(int i = 0;i<object.length;i++){
     
					ps.setObject((i+1),object[i]);
				}
			}
			
			num = ps.executeUpdate();
		} catch (SQLException e) {
     
			e.printStackTrace();
		}finally{
     
			close(conn,ps,null);
		}
		return num;
	}
	/*
	1.查,第一个参数传递是sql语句,第二个参数传递object类型数组
	2.获取连接
	3.得到需要执行aql语句
	4.给占位符赋值
	5.执行sql语句
	6.输出结果
	*/
	public ResultSet getResultSet(String sql,Object[] object){
     
		conn = getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
     
			ps = conn.prepareStatement(sql);
			if(object != null && object.length > 0){
     
				for (int i = 0; i < object.length; i++) {
     
					ps.setObject((i+1),object[i]);
				}
			}
			rs = ps.executeQuery();
		} catch (SQLException e) {
     
			e.printStackTrace();
		}finally{
     
//			因为还要继续使用,先不断开连接
//			close(conn,ps,rs);
		}
		
		return rs;
	}
	/*
	1.关闭资源
	*/
	public void close(Connection conn,PreparedStatement ps,ResultSet rs){
     
		try {
     
			if(conn != null){
     
				conn.close();
			}
			if(ps != null){
     
				ps.cancel();
			}
			if(rs != null){
     
				rs.close();
			}
		} catch (SQLException e) {
     
			e.printStackTrace();
		}
	}	
}

2、创建对象实例
将对象属性封装,创建有参及无参构造,重写toStringa方法

package com.offcn.day03.work;
import java.io.Serializable;

public class Pet implements Serializable{
     
	private int id;
	private String name;
	private int health;
	private int love;
	private String strain;

	public Pet() {
     
		super();
	}
	
	public Pet(int id, String name, int health, int love, String strain) {
     
		super();
		this.id = id;
		this.name = name;
		this.health = health;
		this.love = love;
		this.strain = strain;
	}
	
	
	public int getId() {
     
		return id;
	}
	public void setId(int id) {
     
		this.id = id;
	}
	public String getName() {
     
		return name;
	}
	public void setName(String name) {
     
		this.name = name;
	}
	public int getHealth() {
     
		return health;
	}
	public void setHealth(int health) {
     
		this.health = health;
	}
	public int getLove() {
     
		return love;
	}
	public void setLove(int love) {
     
		this.love = love;
	}
	public String getStrain() {
     
		return strain;
	}
	public void setStrain(String strain) {
     
		this.strain = strain;
	}

	@Override
	public String toString() {
     
		return "Pet [id=" + id + ", name=" + name + ", health=" + health
				+ ", love=" + love + ", strain=" + strain + "]";
	}
}

3、创建petDao层接口,让工具类重写里面的方法

package com.offcn.day03.work;
import java.util.List;

public interface PetDao {
     
	//查询全部
	List<Pet> selectByAll();
	//增加
	int addPet(Pet pet);
	//修改
	int updatePet(Pet pet);
	//删除
	int deletePet(int i);
	//分页查询
	List<Pet> selectByLimit(Integer currentPageNo,Integer PageSize);
	//模糊查询
	List<Pet> selectByLike(String name);
}

4、创建PetDao层接口实现类并继承BaseDao层基类

package com.offcn.day03.work;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class PetDaoImpl extends BaseDao implements PetDao {
     
	 //全部查询
	public List<Pet> selectByAll() {
     
		 //创建集合存储
		List<Pet> plist = new ArrayList<Pet> ();
		String sql = "select * from pet";
		ResultSet rs =  super.getResultSet(sql, null);
		try {
     
			while(rs.next()){
     
				Pet pet = new Pet();
				pet.setId(rs.getInt("id"));
				pet.setName(rs.getString("name"));
				pet.setHealth(rs.getInt("health"));
				pet.setLove(rs.getInt("love"));
				pet.setStrain(rs.getString("strain"));
				plist.add(pet);
			}
		} catch (SQLException e) {
     
			e.printStackTrace();
		}
		
		return plist;
	}
	//用户增加
	public int addPet(Pet pet){
     
		String sql = "insert into pet(name,health,love,strain) values(?,?,?,?)";
		Object[] object = {
     pet.getName(),pet.getHealth(),pet.getLove(),pet.getStrain()};
		int num = super.update(sql, object);
		return num;
	}
	//修改
	public int updatePet(Pet pet) {
     
		String sql = "update pet set name = ?,health = ?,love = ?,strain = ? where id = ? ";
		Object[] object = {
     pet.getName(),pet.getHealth(),pet.getLove(),pet.getStrain(),pet.getId()};
		int num = super.update(sql, object);
		return num;
	}
	//删除
	public int deletePet(int i) {
     
		String sql = "delete from pet where id = ?";
		Object[] object = {
     i};
		int num = super.update(sql, object);
		return num;
	}
	//分页查询
	public List<Pet> selectByLimit(Integer currentPageNo,Integer PageSize) {
     
		List<Pet> plist = new ArrayList<Pet> ();
		String sql = "select * from pet limit ?,?";
		Object[] object = {
     (currentPageNo-1)*PageSize,PageSize};
		ResultSet rs = super.getResultSet(sql, object);
		try {
     
			while(rs.next()){
     
				Pet pet = new Pet();
				pet.setId(rs.getInt("id"));
				pet.setName(rs.getString("name"));
				pet.setHealth(rs.getInt("health"));
				pet.setLove(rs.getInt("love"));
				pet.setStrain(rs.getString("strain"));
				plist.add(pet);
			}
		} catch (SQLException e) {
     
			e.printStackTrace();
		}
		return plist;
	}
	//模糊查询
	public List<Pet> selectByLike(String name) {
     
		List<Pet> plist = new ArrayList<Pet> ();
		String sql = "select * from pet where name like ?";
		Object[] object = {
     name};
		ResultSet rs = super.getResultSet(sql, object);
		
		try {
     
			while(rs.next()){
     
				Pet pet = new Pet();
				pet.setId(rs.getInt("id"));
				pet.setName(rs.getString("name"));
				pet.setHealth(rs.getInt("health"));
				pet.setLove(rs.getInt("love"));
				pet.setStrain(rs.getString("strain"));
				plist.add(pet);
			}
		} catch (SQLException e) {
     
			e.printStackTrace();
		}
		return plist;
	}
}

5、创建测试类

package com.offcn.day03.work;
import java.util.List;

public class PetTest {
     
	public static void main(String[] args) {
     
		//实例化对象
		PetDao petDao = new PetDaoImpl();
		//测试增加
		
		Pet pet = new Pet();
		pet.setName("可达鸭");
		pet.setHealth(80);
		pet.setLove(90);
		pet.setStrain("大黄鸭");
		petDao.addPet(pet);
		
		//测试修改
		
		Pet pet = new Pet();
		pet.setName("小黄鸭");
		pet.setHealth(80);
		pet.setLove(90);
		pet.setStrain("黄鸭");
		pet.setId(5);
		petDao.updatePet(pet);
		
		//测试删除
		
		petDao.deletePet(5);
		
		//测试Limit
		
		List<Pet> LimitList = petDao.selectByLimit(1,3);
		System.out.println(limitlist);
		
		//测试模糊查询
		List<Pet> likeList = petDao.selectByLike("%花%");
		System.out.println(likeList);
	}
}

有问题可联系QQ 237680098进行交流

你可能感兴趣的:(数据库,MySQL,连接数据库,数据库增删改查)