Goods的Dao类

package com.nsu.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.eclipse.swt.internal.win32.UDACCEL;

import com.nsu.bean.Goods;
import com.nsu.util.DButil;

public class GoodsDao {
private Connection conn;
private java.sql.PreparedStatement pst;//pst预处理
private ResultSet rs;
DButil db = new DButil();

//向数据库中添加数据
public boolean addGoods(Goods goods){
boolean b = false;
try {
    conn = db.getConn();
    String sql="insert into goods(goodname,price,num)values('"+goods.getGoodname()+"','"+goods.getPrice()+"','"+goods.getNum()+"')";

    pst=conn.prepareStatement(sql);
    int a = pst.executeUpdate();
    if(a==1){
        b=true;
    }
} catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    
}
return b;
    
}

//向数据库中修改数据
public boolean updGoods(Goods goods){
    boolean b =false;
    try {
        conn = db.getConn();
        String sql = "update goods set id='"+goods.getId()+"',goodname='"+goods.getGoodname()+"',price='"+goods.getPrice()+"',num='"+goods.getNum()+"'";
        pst=conn.prepareStatement(sql);
        int a =pst.executeUpdate();
        if(a==1){
            b=true;
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return b;
    
}

//删除数据库中的数据
public boolean delGoods(int id){
    boolean b=false;
    try {
        conn=db.getConn();
        String sql="delete from goods where id="+id;
        pst=conn.prepareStatement(sql);
        int a =pst.executeUpdate();
        if(a==1){
            b=true;
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return b;
    
}

//查寻数据库的数据
public Goods selectgoodsid(int id){
    Goods goods=new Goods();
    try {
        conn=db.getConn();
        String sql="select*from goods where id="+id;
        pst=conn.prepareStatement(sql);
        rs=pst.executeQuery();
        while (rs.next()) {
            goods.setGoodname(rs.getString(2));
            goods.setId(rs.getInt(1));
            goods.setPrice(rs.getFloat(3));
            goods.setNum(rs.getInt(4));
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return goods;
    
}

public static void main(String [] args){
    GoodsDao gd = new GoodsDao();
    
    //添加数据
    //Goods goods = new Goods();
    //goods.setGoodname("乐视");
    //goods.setNum(5);
    //goods.setPrice(25);
    //System.out.println(gd.addGoods(goods));
    
    //修改数据
    //Goods goods = new Goods();
    //goods.setId(1);
    //goods.setGoodname("小米");
    //goods.setPrice(30);
    //goods.setNum(36);
    //System.out.println(gd.updGoods(goods));
    
    //删除表中数据
    //System.out.println(gd.delGoods(1));
    
    //查询表中数据
    
}

}

你可能感兴趣的:(Goods的Dao类)