前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JDBC的泛化设计

JDBC的泛化设计

作者头像
lonelydawn
发布2018-02-09 11:00:00
5320
发布2018-02-09 11:00:00
举报

在mysql数据库中建立如下数据库及表结构作测试使用:

代码语言:javascript
复制
create database market;
use market;

create table client(
id int primary key AUTO_INCREMENT,
num nvarchar(12) unique,
password varchar(20) not null)engine=innoDB default charset=utf8;

insert into client values(1,'root','root');

在eclipse建立一个工程,工程目录结构如下:

1.ConnectionUtil在进行数据库交互的过程中,只使用数据库对象,而不进行具体对象的操作。

在ConnectionUtil中,放置一些数据库的基本对象:

代码语言:javascript
复制
private Connection conn;
private Statement stat;
private PreparedStatement ps;

在ConnectionUtil的构造器中,进行数据库对象的初始化和数据库的连接:

代码语言:javascript
复制
public ConnectionUtil(String url){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn=DriverManager.getConnection(url);
            stat=conn.createStatement();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

在ConnectionUtil中,另保存一些数据库操作的基本方法:

1).查找

代码语言:javascript
复制
public ResultSet find(String sql){
    try {
        return stat.executeQuery(sql);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

2).删除

代码语言:javascript
复制
public int delete(String sql){
        try {
            return stat.executeUpdate(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }

3).SQL防注入通过id进行的查找和删除操作

代码语言:javascript
复制
public int executeById(String sql,int id){
        try {
            ps=conn.prepareStatement(sql);
            ps.setInt(1,id);
            
            return ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }

4).SQL防注入根据字段定制的更新操作

代码语言:javascript
复制
public int executeUpdate(String sql,String num,String password,int id){
        try {
            ps=conn.prepareStatement(sql);
            ps.setString(1, num);
            ps.setString(2, password);
            ps.setInt(3,id);
            
            return ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }
代码语言:javascript
复制
public int executeUpdate(String sql,int id,String num,String password){
        try {
            ps=conn.prepareStatement(sql);
            ps.setInt(1,id);
            ps.setString(2, num);
            ps.setString(3, password);
            
            return ps.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }

在ConnectionUtil中的收尾工作:

1).关闭Statement

代码语言:javascript
复制
public void close(Statement stat){
        try {
            stat.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

2).关闭Connection

代码语言:javascript
复制
public void close(Connection conn){
        try {
            conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

2.Client类 (JavaBean)在业务处理层保存数据信息

代码语言:javascript
复制
public class Client {
    private int id;
    private String num;
    private String password;
    
    public Client() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Client(int id, String name, String password) {
        super();
        this.id = id;
        this.num = name;
        this.password = password;
    }
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getNum() {
        return num;
    }

    public void setNum(String num) {
        this.num = num;
    }

    public String getPassword() {
        return password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
    
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        result = prime * result + ((num == null) ? 0 : num.hashCode());
        result = prime * result
                + ((password == null) ? 0 : password.hashCode());
        return result;
    }
    
    public String toString() {
        return "client  id=" + id + ", num=" + num + ", password=" + password;
    }
}

3.在ClientDao层将数据库对象转换为具体对象,该处为Client类对象

在ClientDao中保存成员工具对象,类初始化的时候实例化该工具对象

代码语言:javascript
复制
private ConnectionUtil util;
public ClientDao(String url) {
        super();
        util=new ConnectionUtil(url); 
    }

获取所有的Client对象:

代码语言:javascript
复制
public List<Client> queryClients(){
        List<Client> list=new ArrayList<Client>();
        ResultSet set=util.find("select * from client");
        try {
            while(set.next()){
                Client temp=new Client(set.getInt(1),set.getString(2),set.getString(3));
                list.add(temp);
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }
        util.close(set);
        return list;
    }

根据id查找对象:

代码语言:javascript
复制
public Client queryClient(int id){
        Client client=null;
        ResultSet set=util.preparedFindById("select * from client where id=?", id);
        try {
            while(set.next())
                client=new Client(set.getInt(1),set.getString(2),set.getString(3));
        }catch (SQLException e) {
            e.printStackTrace();
        }
        util.close(set);
        return client;
    }

插入Client对象:

代码语言:javascript
复制
public int insertClient(Client client){
        return util.executeUpdate("insert into client values(?,?,?)", client.getId(), client.getNum()    , client.getPassword());
    }

根据id更新client对象:

代码语言:javascript
复制
public int updateClient(Client client){
        return util.executeUpdate("update client set num=?,password=? where id=?",  client.getNum(),client.getPassword(),client.getId());
    }

根据id删除client对象:

代码语言:javascript
复制
public int deleteById(int id){
        return util.executeById("delete from client where id=?", id);
    }

删除所有的client对象:

代码语言:javascript
复制
public int deleteClients(){
        return util.delete("delete from client");
    }

4.最后再写一个测试驱动Tester:

代码语言:javascript
复制
public class Tester {
    private static ClientDao dao = new ClientDao(
            "jdbc:mysql://localhost:3306/market?user=root&password=" +
            "&useUnicode=true&characterEncoding=UTF8");
    
    public static void main(String[] args) {
//        test01();
//        test02();
//        test03();
//        test04();
//        test05();
//        test06();
    }

//    test:queryClients();
    public static void test01(){
        List<Client> list = new ArrayList<Client>();
        list = dao.queryClients();
        System.out.println(list);
    }
    
//    test:queryClient(int id);
    public static void test02(){
        System.out.println(dao.queryClient(1));
    }
    
//    test:insertClient(Client client);
    public static void test03(){
        Client client=new Client(2,"admin","admin");
        if(dao.insertClient(client)==1)
            System.out.println("Insert successfully!");
        else 
            System.out.println("Insert incorrectly!");
    }
    
//    test:updateClient(Client client);
    public static void test04(){
        Client client=new Client(1,"login","login");
        if(dao.updateClient(client)==1)
            System.out.println("Update successfully!");
        else 
            System.out.println("Update incorrectly!");
    }
    
//    test:deleteById(int id);
    public static void test05(){
        if(dao.deleteById(2)==1)
            System.out.println("Delete successfully by id!");
        else 
            System.out.println("Delete incorrectly by id!");
    }
    
//    test:deleteClients();
    public static void test06(){
        if(dao.deleteClients()==1)
            System.out.println("Delete all successfully!");
        else 
            System.out.println("Delete all incorrectly!");
    }
}

下面是测试结果:

在jdbc中可以将数据库对象和具体对象的操作绑定在一起,但是每多一个具体对象就需要多一个dao层的转化类。

本文将数据库操作单独封装在一起,每当多一个具体对象时只需要编写实现对具体对象操作的代码就好了。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档