how2j.cn


工具版本兼容问题
DAO=DataAccess Object

数据访问对象

实际上就是运用了练习-ORM中的思路,把数据库相关的操作都封装在这个类里面,其他地方看不到JDBC的代码


本视频是解读性视频,所以希望您已经看过了本知识点的内容,并且编写了相应的代码之后,带着疑问来观看,这样收获才多。 不建议一开始就观看视频



4分5秒
本视频采用html5方式播放,如无法正常播放,请将浏览器升级至最新版本,推荐火狐,chrome,360浏览器。 如果装有迅雷,播放视频呈现直接下载状态,请调整 迅雷系统设置-基本设置-启动-监视全部浏览器 (去掉这个选项)。 chrome 的 视频下载插件会影响播放,如 IDM 等,请关闭或者切换其他浏览器



步骤 1 : DAO接口   
步骤 2 : HeroDAO   
步骤 3 : 练习-ItemDAO   
步骤 4 : 答案-ItemDAO   

package jdbc; import java.util.List; import charactor.Hero; public interface DAO{ //增加 public void add(Hero hero); //修改 public void update(Hero hero); //删除 public void delete(int id); //获取 public Hero get(int id); //查询 public List<Hero> list(); //分页查询 public List<Hero> list(int start, int count); }
package jdbc;
 
import java.util.List;

import charactor.Hero;
 
public interface DAO{
    //增加
    public void add(Hero hero);
    //修改
    public void update(Hero hero);
    //删除
    public void delete(int id);
    //获取
    public Hero get(int id);
    //查询
    public List<Hero> list();
    //分页查询
    public List<Hero> list(int start, int count);
}
设计类HeroDAO,实现接口DAO

这个HeroDAO和答案-ORM很接近,做了几个改进:
1. 把驱动的初始化放在了构造方法HeroDAO里:

public HeroDAO() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

因为驱动初始化只需要执行一次,所以放在这里更合适,其他方法里也不需要写了,代码更简洁

2. 提供了一个getConnection方法返回连接
所有的数据库操作都需要事先拿到一个数据库连接Connection,以前的做法每个方法里都会写一个,如果要改动密码,那么每个地方都需要修改。 通过这种方式,只需要修改这一个地方就可以了。 代码变得更容易维护,而且也更加简洁。
package jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import charactor.Hero; public class HeroDAO implements DAO{ public HeroDAO() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public Connection getConnection() throws SQLException { return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root", "admin"); } public int getTotal() { int total = 0; try (Connection c = getConnection(); Statement s = c.createStatement();) { String sql = "select count(*) from hero"; ResultSet rs = s.executeQuery(sql); while (rs.next()) { total = rs.getInt(1); } System.out.println("total:" + total); } catch (SQLException e) { e.printStackTrace(); } return total; } public void add(Hero hero) { String sql = "insert into hero values(null,?,?,?)"; try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) { ps.setString(1, hero.name); ps.setFloat(2, hero.hp); ps.setInt(3, hero.damage); ps.execute(); ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) { int id = rs.getInt(1); hero.id = id; } } catch (SQLException e) { e.printStackTrace(); } } public void update(Hero hero) { String sql = "update hero set name= ?, hp = ? , damage = ? where id = ?"; try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) { ps.setString(1, hero.name); ps.setFloat(2, hero.hp); ps.setInt(3, hero.damage); ps.setInt(4, hero.id); ps.execute(); } catch (SQLException e) { e.printStackTrace(); } } public void delete(int id) { try (Connection c = getConnection(); Statement s = c.createStatement();) { String sql = "delete from hero where id = " + id; s.execute(sql); } catch (SQLException e) { e.printStackTrace(); } } public Hero get(int id) { Hero hero = null; try (Connection c = getConnection(); Statement s = c.createStatement();) { String sql = "select * from hero where id = " + id; ResultSet rs = s.executeQuery(sql); if (rs.next()) { hero = new Hero(); String name = rs.getString(2); float hp = rs.getFloat("hp"); int damage = rs.getInt(4); hero.name = name; hero.hp = hp; hero.damage = damage; hero.id = id; } } catch (SQLException e) { e.printStackTrace(); } return hero; } public List<Hero> list() { return list(0, Short.MAX_VALUE); } public List<Hero> list(int start, int count) { List<Hero> heros = new ArrayList<Hero>(); String sql = "select * from hero order by id desc limit ?,? "; try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) { ps.setInt(1, start); ps.setInt(2, count); ResultSet rs = ps.executeQuery(); while (rs.next()) { Hero hero = new Hero(); int id = rs.getInt(1); String name = rs.getString(2); float hp = rs.getFloat("hp"); int damage = rs.getInt(4); hero.id = id; hero.name = name; hero.hp = hp; hero.damage = damage; heros.add(hero); } } catch (SQLException e) { e.printStackTrace(); } return heros; } }
步骤 3 :

练习-ItemDAO

edit  姿势不对,事倍功半! 点击查看做练习的正确姿势
设计一个ItemDAO,实现了DAO接口,提供相应的功能实现Item类的ORM
在查看答案前,尽量先自己完成,碰到问题再来查看答案,收获会更多
在查看答案前,尽量先自己完成,碰到问题再来查看答案,收获会更多
在查看答案前,尽量先自己完成,碰到问题再来查看答案,收获会更多
查看本答案会花费3个积分,您目前总共有点积分。查看相同答案不会花费额外积分。 积分增加办法 或者一次性购买JAVA 中级总计0个答案 (总共需要0积分)
查看本答案会花费3个积分,您目前总共有点积分。查看相同答案不会花费额外积分。 积分增加办法 或者一次性购买JAVA 中级总计0个答案 (总共需要0积分)
账号未激活 账号未激活,功能受限。 请点击激活
本视频是解读性视频,所以希望您已经看过了本答案的内容,带着疑问来观看,这样收获才多。 不建议一开始就观看视频

1分16秒 本视频采用html5方式播放,如无法正常播放,请将浏览器升级至最新版本,推荐火狐,chrome,360浏览器。 如果装有迅雷,播放视频呈现直接下载状态,请调整 迅雷系统设置-基本设置-启动-监视全部浏览器 (去掉这个选项)。 chrome 的 视频下载插件会影响播放,如 IDM 等,请关闭或者切换其他浏览器


1. 给Item类加上id

2. 创建Item表的sql语句

CREATE TABLE item (
id int(11) AUTO_INCREMENT,
name varchar(30) ,
price int,
PRIMARY KEY (id)
) DEFAULT CHARSET=utf8;
答案-ItemDAO
package property; import charactor.LOL; public class Item implements LOL ,Comparable<Item>{ public int id; public String name; public int price; public Item(){ } public Item(String name){ this.name = name; } public void effect(){ System.out.println("物品使用后,可以有效果"); } public boolean disposable() { return false; } @Override public int compareTo(Item o) { return o.price-price; } @Override public String toString() { return "Item [name=" + name + ", price=" + price + "]\r\n"; } }
package jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import property.Item; public class ItemDAO { public ItemDAO() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public Connection getConnection() throws SQLException { return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root", "admin"); } public int getTotal() { int total = 0; try (Connection c = getConnection(); Statement s = c.createStatement();) { String sql = "select count(*) from item"; ResultSet rs = s.executeQuery(sql); while (rs.next()) { total = rs.getInt(1); } System.out.println("total:" + total); } catch (SQLException e) { e.printStackTrace(); } return total; } public void add(Item item) { String sql = "insert into item values(null,?,?)"; try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) { ps.setString(1, item.name); ps.setInt(2, item.price); ps.execute(); ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) { int id = rs.getInt(1); item.id = id; } } catch (SQLException e) { e.printStackTrace(); } } public void update(Item item) { String sql = "update item set name= ?, price = ? where id = ?"; try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) { ps.setString(1, item.name); ps.setInt(2, item.price); ps.setInt(3, item.id); ps.execute(); } catch (SQLException e) { e.printStackTrace(); } } public void delete(int id) { try (Connection c = getConnection(); Statement s = c.createStatement();) { String sql = "delete from item where id = " + id; s.execute(sql); } catch (SQLException e) { e.printStackTrace(); } } public Item get(int id) { Item item = null; try (Connection c = getConnection(); Statement s = c.createStatement();) { String sql = "select * from item where id = " + id; ResultSet rs = s.executeQuery(sql); if (rs.next()) { item = new Item(); String name = rs.getString(2); int price = rs.getInt(3); item.name = name; item.price = price; item.id = id; } } catch (SQLException e) { e.printStackTrace(); } return item; } public List<Item> list() { return list(0, Short.MAX_VALUE); } public List<Item> list(int start, int count) { List<Item> items = new ArrayList<Item>(); String sql = "select * from item order by id desc limit ?,? "; try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) { ps.setInt(1, start); ps.setInt(2, count); ResultSet rs = ps.executeQuery(); while (rs.next()) { Item item = new Item(); int id = rs.getInt(1); String name = rs.getString(2); int price = rs.getInt(3); item.name = name; item.price = price; item.id = id; items.add(item); } } catch (SQLException e) { e.printStackTrace(); } return items; } }
package jdbc; import java.util.List; import property.Item; public class TestDAO { public static void main(String[] args) { ItemDAO dao= new ItemDAO(); List<Item> is =dao.list(); System.out.println("数据库中总共有" + is.size() + " 条数据"); Item i = new Item("新的物品"); System.out.println("新加一条数据"); dao.add(i); is =dao.list(); System.out.println("数据库中总共有" + is.size() + " 条数据"); System.out.println("取出id=4的数据,它的name是:"); i = dao.get(4); System.out.println(i.name); System.out.println("把名字改为 物品X,并且更新到数据库"); i.name="物品X"; dao.update(i); System.out.println("取出id=4的数据,它的name是:"); i = dao.get(4); System.out.println(i.name); System.out.println("删除id=4的数据"); dao.delete(i.id); is =dao.list(); System.out.println("数据库中总共有" + is.size() + " 条数据"); } }


HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。


问答区域    
2024-01-25 ItemDAO-练习
胡乱起个名

关于 JAVA 中级-JDBC-DAO 的提问



设计一个ItemDAO,实现了DAO接口,提供相应的功能实现Item类的ORM
// Interface
public interface IDAO {
	// 统计
	public int count();
	// 增加
	public void add(Item item);
	// 修改
	public void update(Item item);
	// 获取
	public void delete(int id);
	// ***
	public Item get(int id);
	// 查询
	public List<Item> list();
	// 分页查询
	public List<Item> list(int start, int count);
}

// ItemDAO
public class ItemDAO implements IDAO {
	
	public ItemDAO() {
		try {
				Class.forName("com.mysql.jdbc.Driver");
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}	
		}
		
		public Connection getConnection() throws SQLException{
			return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how23java?characterEncoding=UTF-8", "*",
	                "*");
		}
		
		//count
		public int count() {
			int total = 0;
			try {
				Class.forName("com.mysql.jdbc.Driver");			
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} 
			String sql = "select count(*) from hero";
			try(Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/h23java?characterEncoding=UTF-8", "*", "*");				
					Statement s = c.createStatement();
					){
				
	            ResultSet rs = s.executeQuery(sql);
	           
	            while (rs.next()) {
	                total = rs.getInt(1);
	            }
	 
	        } catch (SQLException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
			return total;
		}
		
		@Override
		public void add(Item item) {
			
			String sql = "insert into item values(null,?,?)";
			try(Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/h23java?characterEncoding=UTF-8", "*", "*");				
					PreparedStatement ps = c.prepareStatement(sql);
					){		
				ps.setString(1, item.name);
				ps.setInt(2, item.price);
				ps.execute();
				
				ResultSet rs = ps.getGeneratedKeys();
				if(rs.next()) {
					int id = rs.getInt(1);
					item.id = id;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void update(Item item) {
			
			String sql = "update item set name= ?, price = ? where id = ?";
			try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) {
		  
				ps.setString(1, item.name);
		    	ps.setInt(2, item.price);
		   
		    	ps.execute();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void delete(int id) {
			try(Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/h23java?characterEncoding=UTF-8", "*", "*");				
					Statement s = c.createStatement();
					){
				String sql = "delete from item where id = " + id;
	            s.execute(sql);
	     
	        } catch (SQLException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
		}
		
		public Item get(int id) {
			Item item = null;
			
			try(Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/h23java?characterEncoding=UTF-8", "*", "*");				
					Statement s = c.createStatement();
					){
				
				String sql = "select * from item where id = " + id;
				
				ResultSet rs = s.executeQuery(sql);
				if(rs.next()) {
					item = new Item();
					String name = rs.getString(2);
					int price = rs.getInt(3);
					item.name = name;
					item.price = price;
					item.id = id;
				} 
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return item;
		}
		
		@Override
		public List<Item> list() {
			// TODO 自动生成的方法存根
			return list(0, Short.MAX_VALUE);
		}

		@Override
		public List<Item> list(int start, int count) {
			List<Item> items = new ArrayList<>();
			
			String sql = "select * from item order by id desc limit ?,? ";
			try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) {
				  
				ps.setInt(1, start);
				ps.setInt(2, count);
				
				ResultSet rs = ps.executeQuery();

				while (rs.next()) {
					Item item = new Item();
	                int id = rs.getInt(1);
	                String name = rs.getString(2);
	                int price = rs.getInt(3);
	                item.id = id;
	                item.name = name;
	                item.price = price;
	   
	                items.add(item);
				}
	        } catch (SQLException e) {
	            e.printStackTrace();
	        }
				return items; 		
		}
}

							





回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到





2022-04-13 对id为null的insert语句有疑问
javahack

关于 JAVA 中级-JDBC-DAO 的提问
public void add(Hero hero) { String sql = "insert into hero values(null,?,?,?)"; try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);) { ps.setString(1, hero.name); ps.setFloat(2, hero.hp); ps.setInt(3, hero.damage); ps.execute(); ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) { int id = rs.getInt(1); hero.id = id; } } catch (SQLException e) { e.printStackTrace(); } } 正常数据库中id都是主键,主键都非空的,那这种情况insert into hero values(null,?,?,?)是执行不了的,这个只能把id不设置为主键吗?




2 个答案

四方1
答案时间:2023-07-26
?不是主键会自然增长吧?应该是之前就设置了id 是auto increase了,所以必须给null,要不自然增长就乱了

MAXRAIN
答案时间:2022-07-07
主键添加null会自增长



回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
答案 或者 代码至少填写一项, 如果是自己有问题,请重新提问,否则站长有可能看不到




2021-01-18 临时对象问题
2020-06-18 DAO练习
2020-03-28 为什么在HeroDAO里delete和get没有使用PreparedStatment?


提问太多,页面渲染太慢,为了加快渲染速度,本页最多只显示几条提问。还有 31 条以前的提问,请 点击查看

提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
关于 JAVA 中级-JDBC-DAO 的提问

尽量提供截图代码异常信息,有助于分析和解决问题。 也可进本站QQ群交流: 578362961
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
在已经存在的几千个提问里,有相当大的比例,是因为使用了和站长不同版本的开发环境导致的,比如 jdk, eclpise, idea, mysql,tomcat 等等软件的版本不一致。
请使用和站长一样的版本,可以节约自己大量的学习时间。 站长把教学中用的软件版本整理了,都统一放在了这里, 方便大家下载: https://how2j.cn/k/helloworld/helloworld-version/1718.html

上传截图