package com.shop.util;

import java.sql.*;

//SqlHelper类
//定义了数据库连接函数,关闭查询结果集,关闭Statement对象,关闭数据库连接
//这样的做法是执行上述4个操作时可以直接调用函数(面向对象的思想),可以好好理解一下
public class SqlHelper {
public static Connection getConnection() {
Connection conn = null;

      String driver = "com.mysql.jdbc.Driver";// 驱动
      String url = "jdbc:mysql://127.0.0.1:3306/banksystem";// SqlServer链接地址

        String username = "sa";// 用户名
String password = "sa";// 密码
try {
Class.forName(driver);// 加载驱动类
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
System.out.println("找不到驱动程序类 ,加载驱动失败!");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("数据库连接失败!");
e.printStackTrace();
}
// System.out.println("连接成功");
return conn;
}
//关闭连接
public static void closeConn(Connection conn){
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//关闭执行对象
public static void closeStatement(Statement stmt){
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//关闭结果集
public static void closeResultSet(ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} SqlHelper

商品dao方法的实现。

package com.shop.dao;

import java.sql.*;
import java.util.ArrayList;
import java.util.List; import com.shop.po.Goods;
import com.shop.util.SqlHelper; /**
* GoodsDao接口实现类
*
* @author HP-Developer
*
*/
public class GoodsDaoImpl implements GoodsDao { public int insertGoods(Goods goods) {
Connection conn = null;
//PreparedStatement和Statement的区别在于
//PreparedStatement接口继承Statement,
//PreparedStatement 实例包含已编译的 SQL 语句,所以其执行速度要快于 Statement 对象。
//作为 Statement 的子类,PreparedStatement 继承了 Statement 的所有功能。
//三种方法 execute、 executeQuery 和 executeUpdate 已被更改以使之不再需要参数
//PreparedStatement性能更优,建议使用,但是比较复杂一点 //Statement 是 Java 执行数据库操作的一个重要方法,用于在已经建立数据库连接的基础上,向数据库发送要执行的SQL语句
//使用 Statement 对象执行语句
Statement stmt = null;
int result = 0;
String name=goods.getName();
String kind=goods.getKind();
double price=goods.getPrice();
int stock=goods.getStock();
String des=goods.getDescription();
String sql = "insert into Goods values('"+name+"','"+kind+"','"+price+"','"+stock+"','"+des+"')";
// 访问数据库
try {
// 1获得连接
conn = SqlHelper.getConnection();
// 2执行对象
stmt = conn.createStatement();
// 3执行
result = stmt.executeUpdate(sql); } catch (Exception e) {
//捕捉错误
e.printStackTrace();
} finally {
//关闭操作对象
SqlHelper.closeStatement(stmt);
//关闭连接
SqlHelper.closeConn(conn);
}
//返回受影响的行数
return result;
//try catch finally是一种语句结构
//就我个人的理解,在try中执行操作,catch捕捉错误,finally进行收尾
} //删除和更新与插入类似 ,我就不加注释了
public int deleteGoods(int id) {
Connection conn = null;
Statement stmt = null;
int result = 0;
String sql = "delete from Goods where gID='"+id+"'";
try {
conn = SqlHelper.getConnection();
stmt = conn.createStatement();
result = stmt.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
SqlHelper.closeStatement(stmt);
SqlHelper.closeConn(conn);
} return result;
} public int updateGoods(int id, Goods goods) {
// TODO Auto-generated method stub
Connection conn = null;
Statement stmt = null;
int result = 0;
String name=goods.getName();
String kind=goods.getKind();
double price=goods.getPrice();
int stock=goods.getStock();
String des=goods.getDescription();
String sql = "update Goods set gName='"+name+"',gKind='"+kind+"',gPrice='"+price+"',gNum='"+stock+"',gDes='"+des+"' where gID='"+id+"'";
try {
conn = SqlHelper.getConnection();
stmt = conn.createStatement();
result = stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
SqlHelper.closeStatement(stmt);
SqlHelper.closeConn(conn);
}
return result;
} //查询全部商品
//因为是多个对象,采用返回List的方式,返回Goods对象的集合
public List<Goods> findAll() {
Connection conn=null;
Statement stmt=null;
//创建对象集合
List gdList = new ArrayList();
ResultSet rs=null;
String sql="select * from Goods";
try{
conn=SqlHelper.getConnection();
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
while(rs.next()){
//创建单个对象
Goods gd = new Goods();
gd.setId(rs.getInt("gID"));
gd.setName(rs.getString("gName"));
gd.setKind(rs.getString("gKind"));
gd.setPrice(rs.getDouble("gPrice"));
gd.setStock(rs.getInt("gNum"));
gd.setDescription(rs.getString("gDes"));
//将此对象存入集合中,昨天闫老师带我们学习了ArrayList,add方法大家应该不陌生
gdList.add(gd);
}
}
catch(SQLException e){
e.printStackTrace();
}
finally{
SqlHelper.closeResultSet(rs);//关闭结果集
SqlHelper.closeStatement(stmt);//关闭Statement对象
SqlHelper.closeConn(conn);//关闭连接
//注意关闭的顺序不能
}
return gdList;
} public Goods findById(int id) {
Connection conn=null;
Statement stmt=null;
//在判断商品存在后再new对象,这样规范
Goods gd = null;
ResultSet rs=null;//定义数据集ResultSet 接受stmt.executeQuery(sql)的返回值
String sql="select * from Goods where gID='"+id+"'";
try{
conn=SqlHelper.getConnection();
stmt=conn.createStatement();
//gd=(Goods)stmt.executeQuery(sql);stmt.executeQuery(sql)的返回值是一个结果集ResultSet
//因为返回的记录是一条,之前想用强制转换的方法实现返回一个商品(Goods)对象,但是不可行,这条代码错误,下面给出正确的操作
rs=stmt.executeQuery(sql);
if(rs.next()){
gd=new Goods();
gd.setId(rs.getInt("gID"));
gd.setName(rs.getString("gName"));
gd.setKind(rs.getString("gKind"));
gd.setPrice(rs.getDouble("gPrice"));
gd.setStock(rs.getInt("gNum"));
gd.setDescription(rs.getString("gDes"));
}
else{
//这样返回一个空商品对象,节省了即使对象为空还赋值的多余操作
return gd;
}
}
catch(SQLException e){
e.printStackTrace();
}
finally{
SqlHelper.closeResultSet(rs);//关闭结果集
SqlHelper.closeStatement(stmt);//关闭
SqlHelper.closeConn(conn);//关闭数据库连接
}
return gd;
}
} GoodsDaoImpl

代码转载于:http://www.cnblogs.com/wangkaipeng/p/4725548.html。

不做讲解,仅用于使用。

最新文章

  1. Mycat 月分片方法
  2. 【开源】OSharp框架解说系列(1):总体设计及系列导航
  3. Win10 UWP系列:更新UWP时注意的问题——TargetDeviceFamily
  4. 浅谈MySQL数据类型
  5. Python学习【第十篇】基础之杂货铺
  6. 【XLL API 函数】xlGetHwnd
  7. 删除指定的文件.bat
  8. lua定时器与定时任务的接口设计
  9. 使用FlashFXP V3.8烈火汉化绿色版软件连接Linux
  10. 解决 .NET Core 中 GetHostAddressesAsync 引起的 EnyimMemcached 死锁问题
  11. PEP8中文翻译(转)
  12. python字符串内置方法
  13. 【python小练习】简单的猜数字游戏
  14. 最难解的耦合 — James
  15. Gym 102056I - Misunderstood … Missing - [DP][The 2018 ICPC Asia-East Continent Final Problem I]
  16. iframe父页面获取iframe子页面的元素 与 iframe子页面获取父页面元素
  17. 中国移动DNS IP地址大全(32个省)
  18. 6 Django系列之关于models的sql语句日常用法总结
  19. RTCM32编解码中的一些概念及相关文献阅读
  20. [Python] numpy.Matrix

热门文章

  1. Maven 3.3.3 Win10环境下的使用实例(下)
  2. iOS基础框架的搭建/国际化操作
  3. 【leetcode】Shortest Palindrome(hard)★
  4. October 13th 2016 Week 42nd Thursday
  5. 添加本地jar到Maven库
  6. C/C++中调用python文件
  7. Codeforces Round #344 (Div. 2)(按位或运算)
  8. Linux安装xwindow图形界面
  9. ActiveMQ的几种集群配置
  10. js自定义延迟执行函数