自由编程打卡,请老师检查!
来源:9-2 自由编程
Mycheol
2020-08-28 00:35:47
package com.imooc.jdbc.goodsapp; import java.util.Date; /** * Goods实体类 */ public class Goods { public Goods(){ } private String name; private float price; private String desp; private Date create_time; public String getName() { return name; } public void setName(String name) { this.name = name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getDesp() { return desp; } public void setDesp(String desp) { this.desp = desp; } public Date getCreate_time() { return create_time; } public void setCreate_time(Date create_time) { this.create_time = create_time; } @Override public String toString() { return "Goods [name=" + name + ", price=" + price + ", desp=" + desp + ", create_time=" + create_time + ']'; } }
package com.imooc.jdbc.goodsapp; import com.alibaba.druid.pool.DruidDataSourceFactory; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import javax.sql.DataSource; import java.io.FileInputStream; import java.net.URLDecoder; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.Properties; public class GoodsQuery { private static void update() { Properties properties = new Properties(); String propertyFlie = GoodsQuery.class.getResource("/druid-config.properties").getPath(); Connection conn = null; try { propertyFlie = new URLDecoder().decode(propertyFlie, "UTF-8"); properties.load(new FileInputStream(propertyFlie)); DataSource dataSource = DruidDataSourceFactory.createDataSource(properties); conn = dataSource.getConnection(); conn.setAutoCommit(false); String sql = "insert into goods (name,price,desp,create_time) values (?,?,?,?)"; QueryRunner qr = new QueryRunner(); qr.update(conn, sql, new Object[]{"照相机", 5000, "放水,索尼", "1999/01/30"}); conn.commit(); query(); } catch (Exception e) { e.printStackTrace(); try { if (conn != null && !conn.isClosed()) { conn.rollback(); System.out.println("添加失败!"); } } catch (SQLException e1) { e1.printStackTrace(); } } finally { try { if (conn != null && !conn.isClosed()) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } private static void query() { Properties properties = new Properties(); String propertyFlie = GoodsQuery.class.getResource("/druid-config.properties").getPath(); Connection conn = null; String str = null; try { propertyFlie = new URLDecoder().decode(propertyFlie, "UTF-8"); properties.load(new FileInputStream(propertyFlie)); DataSource dataSource = DruidDataSourceFactory.createDataSource(properties); QueryRunner qr = new QueryRunner(dataSource); List<Goods> list = qr.query("select * from goods", new BeanListHandler<>(Goods.class)); for (Goods gds : list) { System.out.println(gds.toString()); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { update(); } }
1回答
同学你好,练习题完成的不错,很棒,继续加油
祝学习愉快
相似问题