• JDBC实战案例--利用jdbc实现的宠物信息管理系统


    一、需求:

    利用jdbc实现对宠物的信息进行管理的一套系统

    宠物信息:宠物ID,宠物类别,宠物名字,宠物性别,宠物年龄,宠物入库日期

    系统完成功能:实现对宠物信息的录入,修改,删除,查询。

    二、解决方案

    一共创建了四个类:

    1.一个宠物类PetMessage 里面是宠物的信息  

    2.一个是数据库连接类DBUtil  里面主要是完成数据连接功能   

    3.一个是宠物管理类PetDAO  完成对宠物信息的增删该查  

    4.最后一个就是一个测试类PetTest 

    完成对系统的测试

    三、具体实现:

    新建一个java项目,并导入需要用到的包。如下图:

    宠物类PetMessage

     1 package com.daliu.jdbc;
     2 
     3 /**
     4  * 宠物信息类
     5  *
     6  */
     7 public class PetMessage {
     8     
     9     //1.定义宠物的属性
    10     // 宠物信息:宠物ID,宠物类别,宠物名字,宠物性别,宠物年龄,宠物入库日期
    11     private int petId;
    12     private String petSort;
    13     private String petName;
    14     private String petSex;
    15     private int petAge;
    16     private String petDate;
    17     
    18     //2.生成一个无参构造方法和有参构造方法
    19     
    20     public PetMessage(){}
    21     
    22     public PetMessage(int petId, String petSort, String petName, String petSex,
    23             int petAge, String petDate) {
    24         super();
    25         this.petId = petId;
    26         this.petSort = petSort;
    27         this.petName = petName;
    28         this.petSex = petSex;
    29         this.petAge = petAge;
    30         this.petDate = petDate;
    31     }
    32     
    33     
    34     //3.生成属性的get,set方法
    35     public int getPetId() {
    36         return petId;
    37     }
    38     public void setPetId(int petId) {
    39         this.petId = petId;
    40     }
    41     public String getPetSort() {
    42         return petSort;
    43     }
    44     public void setPetSort(String petSort) {
    45         this.petSort = petSort;
    46     }
    47     public String getPetName() {
    48         return petName;
    49     }
    50     public void setPetName(String petName) {
    51         this.petName = petName;
    52     }
    53     public String getPetSex() {
    54         return petSex;
    55     }
    56     public void setPetSex(String petSex) {
    57         this.petSex = petSex;
    58     }
    59     public int getPetAge() {
    60         return petAge;
    61     }
    62     public void setPetAge(int petAge) {
    63         this.petAge = petAge;
    64     }
    65     public String getPetDate() {
    66         return petDate;
    67     }
    68     public void setPetDate(String petDate) {
    69         this.petDate = petDate;
    70     }
    71 
    72     //4.属性的toString方法,并改进为自己所要的样子
    73     @Override
    74     public String toString() {
    75         return "PetMessage [petId=" + petId + ", petSort=" + petSort
    76                 + ", petName=" + petName + ", petSex=" + petSex + ", petAge="
    77                 + petAge + ", petDate=" + petDate + "]";
    78     }
    79 }

    数据库连接类DBUtil 

      1 package com.daliu.jdbc;
      2 
      3 import java.io.InputStream;
      4 import java.sql.Connection;
      5 import java.sql.SQLException;
      6 import java.util.Properties;
      7 
      8 import org.apache.commons.dbcp.BasicDataSource;
      9 
     10 /**
     11  * 使用连接池技术管理数据库连接
     12  */
     13 public class DBUtil {
     14 
     15     // 数据库连接池
     16     private static BasicDataSource dbcp;
     17 
     18     // 为不同线程管理连接
     19     private static ThreadLocal<Connection> tl;
     20 
     21     // 通过配置文件来获取数据库参数
     22     static {
     23         try {
     24             Properties prop = new Properties();
     25 
     26             InputStream is = DBUtil.class.getClassLoader().getResourceAsStream(
     27                     "com/daliu/jdbc/db.properties");
     28 
     29             prop.load(is);
     30             is.close();
     31 
     32             // 一、初始化连接池
     33             dbcp = new BasicDataSource();
     34 
     35             // 设置驱动 (Class.forName())
     36             dbcp.setDriverClassName(prop.getProperty("jdbc.driver"));
     37             // 设置url
     38             dbcp.setUrl(prop.getProperty("jdbc.url"));
     39             // 设置数据库用户名
     40             dbcp.setUsername(prop.getProperty("jdbc.user"));
     41             // 设置数据库密码
     42             dbcp.setPassword(prop.getProperty("jdbc.password"));
     43             // 初始连接数量
     44             dbcp.setInitialSize(Integer.parseInt(prop.getProperty("initsize")));
     45             // 连接池允许的最大连接数
     46             dbcp.setMaxActive(Integer.parseInt(prop.getProperty("maxactive")));
     47             // 设置最大等待时间
     48             dbcp.setMaxWait(Integer.parseInt(prop.getProperty("maxwait")));
     49             // 设置最小空闲数
     50             dbcp.setMinIdle(Integer.parseInt(prop.getProperty("minidle")));
     51             // 设置最大空闲数
     52             dbcp.setMaxIdle(Integer.parseInt(prop.getProperty("maxidle")));
     53             // 初始化线程本地
     54             tl = new ThreadLocal<Connection>();
     55         } catch (Exception e) {
     56             System.out.println("初始化失败,请检查配置文件是否符合!");
     57             e.printStackTrace();
     58         }
     59     }
     60 
     61     /**
     62      * 获取数据库连接
     63      * 
     64      * @return
     65      * @throws SQLException
     66      */
     67     public static Connection getConnection() throws SQLException {
     68         /*
     69          * 通过连接池获取一个空闲连接
     70          */
     71         Connection conn = dbcp.getConnection();
     72         tl.set(conn);
     73         return conn;
     74     }
     75 
     76     /**
     77      * 关闭数据库连接
     78      */
     79     public static void closeConnection() {
     80         try {
     81             Connection conn = tl.get();
     82             if (conn != null) {
     83                 /*
     84                  * 通过连接池获取的Connection 的close()方法实际上并没有将 连接关闭,而是将该链接归还。
     85                  */
     86                 conn.close();
     87                 tl.remove();
     88             }
     89         } catch (Exception e) {
     90             System.out.println("释放资源失败!");
     91             e.printStackTrace();
     92             throw new RuntimeException(e);
     93         }
     94     }
     95 
     96     /**
     97      * 测试是否连接成功
     98      * 
     99      * @param args
    100      * @throws SQLException
    101      */
    102     public static void main(String[] args) throws SQLException {
    103         System.out.println(getConnection());
    104     }
    105 }

    宠物管理类PetDAO 

      1 package com.daliu.jdbc;
      2 
      3 import java.sql.Connection;
      4 import java.sql.ResultSet;
      5 import java.sql.SQLException;
      6 import java.sql.Statement;
      7 
      8 /**
      9  * 宠物信息操作类
     10  * 
     11  */
     12 public class PetDAO {
     13 
     14     // 1.增添宠物信息
     15     public static void doAdd(PetMessage pet) {
     16 
     17         // (1)通过宠物信息类获得宠物信息的定义
     18         int petId = pet.getPetId();
     19         String petSort = pet.getPetSort();
     20         String petName = pet.getPetName();
     21         String petSex = pet.getPetSex();
     22         int petAge = pet.getPetAge();
     23         String petDate = pet.getPetDate();
     24 
     25         // (2)与数据库连接
     26         Connection con = null;
     27         try {
     28             con = DBUtil.getConnection();
     29         } catch (SQLException e1) {
     30             e1.printStackTrace();
     31         }
     32         
     33         
     34         // (3)创建会话,执行sql语句
     35         try {
     36             Statement stmt = con.createStatement();
     37             // 定义sql语句
     38             String sqlString = "insert into petmessage(petid,petsort,petname,petsex,petage,petdate) values("
     39                     + pet.getPetId()
     40                     + ",'"
     41                     + pet.getPetSort()
     42                     + "','"
     43                     + pet.getPetName()
     44                     + "','"
     45                     + pet.getPetSex()
     46                     + "',"
     47                     + pet.getPetAge() 
     48                     + ",'" 
     49                     + pet.getPetDate() + "');";
     50             
     51             // (4)执行sql语句
     52             stmt.execute(sqlString);
     53             
     54             //(5)给出相应的提示
     55             System.out.println("********************");
     56             System.out.println("宠物添加成功!(^o^)");
     57             System.out.println("********************");
     58             
     59             //(6)最后释放资源
     60             DBUtil.closeConnection();
     61             
     62             
     63         } catch (SQLException e) {
     64             // TODO 自动生成 catch 块
     65             System.out.println("增加失败!");
     66             e.printStackTrace();
     67 
     68         }
     69     }
     70 
     71     //2. 根据宠物ID删除宠物信息
     72     public static void doDeleteWithId(PetMessage pet) {
     73         
     74         //1.获得改宠物的信息
     75         int petId = pet.getPetId();
     76         String petSort = pet.getPetSort();
     77         String petName = pet.getPetName();
     78         String petSex = pet.getPetSex();
     79         int petAge = pet.getPetAge();
     80         String petDate = pet.getPetDate();
     81 
     82         // 2.建立数据库连接
     83         Connection con = null;
     84         try {
     85             con = DBUtil.getConnection();
     86         } catch (SQLException e1) {
     87             e1.printStackTrace();
     88         }
     89         //3. 建立会话 ,执行sql语句
     90         try {
     91             Statement stmt = con.createStatement();
     92             // 定义sql语句
     93             String sqlString = "delete from petmessage where petid="
     94                     + pet.getPetId() + ";";
     95             
     96             // 执行sql语句
     97             stmt.execute(sqlString);
     98             
     99             //给出相应的提示
    100             System.out.println("********************");
    101             System.out.println("宠物删除成功!(^o^)");
    102             System.out.println("********************");
    103             
    104             //关闭资源
    105             DBUtil.closeConnection();
    106             
    107         } catch (SQLException e) {
    108             // TODO 自动生成 catch 块
    109             System.out.println("根据宠物ID删除宠物信息失败!");
    110             e.printStackTrace();
    111         }
    112     }
    113 
    114     // 3.根据宠物名字删除宠物信息
    115     public static void doDeleteWithName(PetMessage pet) {
    116         
    117         //(1)获取宠物的信息
    118         int petId = pet.getPetId();
    119         String petSort = pet.getPetSort();
    120         String petName = pet.getPetName();
    121         String petSex = pet.getPetSex();
    122         int petAge = pet.getPetAge();
    123         String petDate = pet.getPetDate();
    124 
    125         // (2)建立数据库连接
    126         Connection con = null;
    127         try {
    128             con = DBUtil.getConnection();
    129         } catch (SQLException e1) {
    130             e1.printStackTrace();
    131         }
    132         // (3)建立会话,执行sql语句
    133         try {
    134             Statement stmt = con.createStatement();
    135             // 定义sql语句
    136             String sqlString = "delete from petmessage where petName="
    137                     + pet.getPetName() + ";";
    138             // 执行sql语句
    139             stmt.execute(sqlString);
    140             //给出提示
    141             System.out.println("********************");
    142             System.out.println("宠物删除成功!(^o^)");
    143             System.out.println("********************");
    144             //关闭资源
    145             DBUtil.closeConnection();
    146             
    147         } catch (SQLException e) {
    148             // TODO 自动生成 catch 块
    149             System.out.println("根据宠物名字删除宠物信息失败!");
    150             e.printStackTrace();
    151         }
    152     }
    153 
    154     // 4.根据宠物ID修改宠物信息
    155     public static void doUpdateWithID(PetMessage pet) {
    156         //(1)获取宠物信息
    157         int petId = pet.getPetId();
    158         String petSort = pet.getPetSort();
    159         String petName = pet.getPetName();
    160         String petSex = pet.getPetSex();
    161         int petAge = pet.getPetAge();
    162         String petDate = pet.getPetDate();
    163 
    164         // (2)建立数据库连接
    165         Connection con = null;
    166         try {
    167             con = DBUtil.getConnection();
    168         } catch (SQLException e1) {
    169             e1.printStackTrace();
    170         }
    171         // (3)建立会话,执行sql语句
    172         try {
    173             Statement stmt = con.createStatement();
    174             // 定义sql语句
    175             String sqlString = "update petmessage set petName='"
    176                     + pet.getPetName() + "' where petId=" + pet.getPetId()
    177                     + ";";
    178             // 执行sql语句
    179             stmt.execute(sqlString);
    180             //给出相应的提示
    181             System.out.println("**********************");
    182             System.out.println("宠物信息修改成功!(^o^)");
    183             System.out.println("**********************");
    184             //关闭资源
    185             DBUtil.closeConnection();
    186         } catch (SQLException e) {
    187             // TODO 自动生成 catch 块
    188             System.out.println("根据宠物ID修改宠物信息失败");
    189             e.printStackTrace();
    190         }
    191     }
    192 
    193     // 5.根据宠物名字修改宠物信息
    194     public static void doUpdateWithName(PetMessage pet) {
    195         //(1)获取宠物信息
    196         int petId = pet.getPetId();
    197         String petSort = pet.getPetSort();
    198         String petName = pet.getPetName();
    199         String petSex = pet.getPetSex();
    200         int petAge = pet.getPetAge();
    201         String petDate = pet.getPetDate();
    202 
    203         // (2)建立数据库连接
    204         Connection con = null;
    205         try {
    206             con = DBUtil.getConnection();
    207         } catch (SQLException e1) {
    208             e1.printStackTrace();
    209         }
    210         // (3)建立会话,执行sql语句
    211         try {
    212             Statement stmt = con.createStatement();
    213             // 定义sql语句
    214             String sqlString = "update petmessage set petAge='"
    215                     + pet.getPetAge() + "' where petName=" + pet.getPetName()
    216                     + ";";
    217             // 执行sql语句
    218             stmt.execute(sqlString);
    219             //给出相应的提示
    220             System.out.println("**********************");
    221             System.out.println("宠物信息修改成功!(^o^)");
    222             System.out.println("**********************");
    223             //关闭资源
    224             DBUtil.closeConnection();
    225         } catch (SQLException e) {
    226             // TODO 自动生成 catch 块
    227             System.out.println("据宠物名字修改宠物信息失败");
    228             e.printStackTrace();
    229         }
    230     }
    231 
    232     // 6.按ID查询宠物信息
    233     public static void doSelectWithId(PetMessage pet) {
    234         //(1)获取宠物信息
    235         int petId = pet.getPetId();
    236         String petSort = pet.getPetSort();
    237         String petName = pet.getPetName();
    238         String petSex = pet.getPetSex();
    239         int petAge = pet.getPetAge();
    240         String petDate = pet.getPetDate();
    241         // (2)建立数据库连接
    242         Connection con = null;
    243         try {
    244             con = DBUtil.getConnection();
    245         } catch (SQLException e1) {
    246             // TODO Auto-generated catch block
    247             e1.printStackTrace();
    248         }
    249         try {
    250             // (3)创建语句对象
    251             Statement stmt = con.createStatement();
    252             // (4)定义sql语句
    253             String sqlString = "select * from petMessage where petId="
    254                     + pet.getPetId() + ";";
    255             //(5) 创建结果集 并执行sql语句
    256             ResultSet rs = stmt.executeQuery(sqlString);
    257             //(6)对结果集进行解析
    258             System.out.println("查询结果如下:");
    259             while (rs.next()) {
    260                 System.out.println("宠物ID: " + rs.getInt("petId") + "   宠物种类:"
    261                         + rs.getString("petSort") + "   宠物名字:"
    262                         + rs.getString("petName") + "   宠物性别:"
    263                         + rs.getString("petSex") + "   宠物年龄:"
    264                         + rs.getInt("petAge") + "   宠物入库时间:"
    265                         + rs.getString("petDate"));
    266             }
    267             
    268             //(7)关闭相应的资源
    269             DBUtil.closeConnection();
    270         } catch (SQLException e) {
    271             // TODO 自动生成 catch 块
    272             System.out.println("按ID查询宠物信息失败");
    273             e.printStackTrace();
    274         }
    275     }
    276 
    277     // 7.按名字查询宠物信息
    278     public static void doSelectWithName(PetMessage pet) {
    279         //(1)获取宠物信息
    280         int petId = pet.getPetId();
    281         String petSort = pet.getPetSort();
    282         String petName = pet.getPetName();
    283         String petSex = pet.getPetSex();
    284         int petAge = pet.getPetAge();
    285         String petDate = pet.getPetDate();
    286         // (2)建立数据库连接
    287         Connection con = null;
    288         try {
    289             con = DBUtil.getConnection();
    290         } catch (SQLException e1) {
    291             // TODO Auto-generated catch block
    292             e1.printStackTrace();
    293         }
    294         try {
    295             // (3)创建语句对象
    296             Statement stmt = con.createStatement();
    297             //(4) 定义sql语句
    298             String sqlString = "select * from petMessage where petName='"
    299                     + pet.getPetName() + "';";
    300             // (5)创建结果集 并执行sql语句
    301             ResultSet rs = stmt.executeQuery(sqlString);
    302             // (6)对结果集进行解析
    303             System.out.println("查询结果如下:");
    304             while (rs.next()) {
    305                 System.out.println("宠物ID: " + rs.getInt("petId") + "   宠物种类:"
    306                         + rs.getString("petSort") + "   宠物名字:"
    307                         + rs.getString("petName") + "   宠物性别:"
    308                         + rs.getString("petSex") + "   宠物年龄:"
    309                         + rs.getInt("petAge") + "   宠物入库时间:"
    310                         + rs.getString("petDate"));
    311             }
    312             // (7)关闭所以对象
    313             DBUtil.closeConnection();
    314         } catch (SQLException e) {
    315             // TODO 自动生成 catch 块
    316             System.out.println("按名字查询宠物信息失败!");
    317             e.printStackTrace();
    318         }
    319     }
    320 }

    测试类PetTest 

     1 package com.daliu.jdbc;
     2 
     3 public class PetTest {
     4     public static void main(String[] args) {
     5 
     6         // 测试数据
     7         // PetMessage pet=new
     8         // PetMessage(1,"leopard","小豹子","female",5,"2014-12-19");
     9         // PetMessage pet1=new
    10         // PetMessage(1,"Dog","小狗狗","female",6,"2014-12-20");
    11         // PetMessage pet2=new
    12         // PetMessage(1,"Cat","小咪咪","female",7,"2014-12-21");
    13         // PetMessage pet3=new
    14         // PetMessage(1,"mouse","小老鼠","female",8,"2014-12-22");
    15         // PetMessage pet4=new
    16         // PetMessage(1,"elephant","大象","female",9,"2014-12-23");
    17         // PetMessage pet5=new
    18         // PetMessage(1,"swan","天鹅","female",10,"2014-12-24");
    19 
    20         // 功能测试:
    21 
    22         // ****1.增添宠物信息 ********
    23         // PetDAO.doAdd(pet);
    24         // PetDAO.doAdd(pet1);
    25         // PetDAO.doAdd(pet2);
    26         // PetDAO.doAdd(pet3);
    27         // PetDAO.doAdd(pet4);
    28         // PetDAO.doAdd(pet5);
    29 
    30         // ****2. 根据宠物ID删除宠物信息 ********
    31         PetMessage pet = new PetMessage(1, "leopard", "小豹子", "female", 5,
    32                 "2014-12-19");
    33         pet.setPetId(1);
    34         PetDAO.doSelectWithId(pet);
    35 
    36         // ****3.根据宠物名字查询宠物信息 ********
    37         // PetMessage pet = new PetMessage(1, "leopard", "小豹子", "female", 5,
    38         // "2014-12-19");
    39         // pet.setPetName("小老鼠");
    40         // PetDAO.doSelectWithName(pet);
    41 
    42         // ****4.根据宠物ID修改宠物信息****
    43         // PetDAO.doUpdateWithID(pet);
    44 
    45         // ****5.根据宠物名字修改宠物信息****
    46         // PetDAO.doUpdateWithName(pet);
    47 
    48         // ****6.根据宠物ID修改宠物信息****
    49         // PetDAO.doDeleteWithId(pet);
    50         // ****7.根据宠物名字修改宠物信息****
    51         // PetDAO.doDeleteWithName(pet);
    52     }
    53 }

    一些测试效果:

    SQL脚本:

     1 create database PegSystem;
     2 
     3 use PegSystem;
     4 
     5 create table pet(
     6 
     7     #private int petId;
     8     #private String petSort;
     9     
    10     #private String petName;
    11     #private String petSex;
    12     #private int petAge;
    13     #private String petDate;
    14 
    15     petId int(7),
    16     petSort varchar(20),
    17     petName varchar(20),
    18     petAge int(4),
    19     petDate  varchar(20)
    20 );
    21 
    22 #select * from pet;
    23 
    24 rename table pet to petMessage;
    25 
    26 #select * from petMessage;
    27 
    28 alter table  petMessage add( petsex varchar(20));
    29 
    30 desc petMessage;
    31 
    32 select * from petMessage;

    配置文件:

    1 jdbc.driver=com.mysql.jdbc.Driver
    2 jdbc.url=jdbc:mysql://localhost:3306/PegSystem
    3 jdbc.user=root
    4 jdbc.password=123456
    5 initsize=1
    6 maxactive=1
    7 maxwait=5000
    8 maxidle=1
    9 minidle=1

    作者:daliu_it
    出处:http://www.cnblogs.com/liuhongfeng/p/4173775.html
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。谢谢合作。

  • 相关阅读:
    线程同步(二)—— 条件变量
    线程同步(一)—— 互斥锁
    进程同步(四)—— 消息队列
    Nginx反向代理服务器的配置
    散列表(hash表)
    浅谈bitmap
    进程空间分配和堆栈大小
    拓扑排序
    归并排序
    快速排序
  • 原文地址:https://www.cnblogs.com/liuhongfeng/p/4173775.html
Copyright © 2020-2023  润新知