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。

不做讲解,仅用于使用。

java jdbc sqlhelper的更多相关文章

  1. 纯Java JDBC连接数据库,且用JDBC实现增删改查的功能

    Java JDBC连接数据库 package cn.cqvie.yjq; import java.sql.*; /** * 注册数据库的驱动程序,并得到数据库的连接对象 * @author yu * ...

  2. JAVA版SqlHelper

    //JAVA版SqlHelper package com.test.Dao; import java.sql.Connection; import java.sql.DriverManager; im ...

  3. java jdbc 连接mysql数据库 实现增删改查

    好久没有写博文了,写个简单的东西热热身,分享给大家. jdbc相信大家都不陌生,只要是个搞java的,最初接触j2ee的时候都是要学习这么个东西的,谁叫程序得和数据库打交道呢!而jdbc就是和数据库打 ...

  4. Java JDBC高级特性

    1.JDBC批处理 实际开发中需要向数据库发送多条SQL语句,这时,如果逐条执行SQL语句,效率会很低,因此可以使用JDBC提供的批处理机制.Statement和PreparedStatemen都实现 ...

  5. Java JDBC下执行SQL的不同方式、参数化预编译防御

    相关学习资料 http://zh.wikipedia.org/wiki/Java数据库连接 http://lavasoft.blog.51cto.com/62575/20588 http://blog ...

  6. Java JDBC批处理插入数据操作

    在此笔记里,我们将看到我们如何可以使用像Statement和PreparedStatement JDBC API来批量在任何数据库中插入数据.此外,我们将努力探索一些场景,如在内存不足时正常运行,以及 ...

  7. Java JDBC批处理插入数据操作(转)

    在此笔记里,我们将看到我们如何可以使用像Statement和PreparedStatement JDBC API来批量在任何数据库中插入数据.此外,我们将努力探索一些场景,如在内存不足时正常运行,以及 ...

  8. java jdbc使用配置文件连接数据库:

    java jdbc使用配置文件连接数据库: 创建后缀名为:.properties的文件,文件内容包括,数据库驱动.连接的数据库地址.用户名.密码…… 以Mysql为例创建config.properti ...

  9. Java JDBC中,MySQL字段类型到JAVA类型的转换

    1. 概述 在使用Java JDBC时,你是否有过这样的疑问:MySQL里的数据类型到底该选择哪种Java类型与之对应?本篇将为你揭开这个答案. 2. 类型映射  java.sql.Types定义了常 ...

随机推荐

  1. Android应用主题与横竖屏的切换

    很多App,现在都具有了横竖屏切换的功能,或者说"白天"和"黑夜"主题的切换. 实现起来也非常简单.主要需要注意的是,在切换的同时,页面的数据不能丢失,不然给用 ...

  2. JAVA回调接口的理解

    A类持有B接口的对象引用,B接口有一个callBack()方法,C类是B类的实现类,实现了callBack()方法,把C类传入A类,当A类执行完操作后调用callBack()方法,这时候A调用的就是C ...

  3. EF-实体更新

    1.数据库表增加字段,EF更新视图后,对应的实体对象没有新增的字段原因:edmx文件右键属性设置了 保存时转换相关的文本模板-false...正确的应该是rue 2. 更改视图后(或者更改字段类型?) ...

  4. 【leetcode】Largest Number ★

    Given a list of non negative integers, arrange them such that they form the largest number. For exam ...

  5. linux 用户、用户组不能是全数字

    今天封装命令行,需要创建用户.用户组,遇到下面问题,如图: 当时我和迷茫,为什么明明存在‘1111’这个用户组,但是却提示不存在呢??难道是linux的一个bug??? 接着我又试了几个: 发现规律了 ...

  6. addsubview跟insertsubview的区别

    子视图是以栈的方式存放的. 每次addsubview时都是在最后面添加. 每次在addsubview前和addsubview后可以看看[self.view.subViews count]: 你看看你的 ...

  7. tableView性能优化

    针对滑动时出现卡的现象 参考:http://blog.sina.cn/dpool/blog/s/blog_b638dc890101ep3x.html?plg_nld=1&plg_auth=1& ...

  8. !对c++类的理解

    c++的类可以分为两类,一种是entity的类(i.e.,实体类),一种是function的类(i.e.,功能类). 对于构造entity的类,包括这种entity的属性已经它本身具备的功能: 而fu ...

  9. iphone删除自动更新的系统

    1.利用 etc/host 文件屏蔽 Apple 更新服务器用电脑 iTools 或者手机 iFile 打开 etc/host 文件,添加:127.0.0.1 mesu.apple.com到文件中.2 ...

  10. 你知道吗?Web的26项基本概念和技术

    这是我在网上看到一篇不错的文章,拿出来与大家分享一下:希望有所帮助 作者: 小鱼  来源: 前端里  发布时间: 2014-08-01 22:56  阅读: 10477 次  推荐: 51   原文链 ...