zoukankan      html  css  js  c++  java
  • jabc_DAO

    JDBC(Java Data Base Connection)的作用是连接数据库

    先看下jdbc连接SQLServer数据库的简单例子

    代码实现(FirstJDBC):

    [java] view plain copy
     
    1. package com.jdbc;  
    2.   
    3. import java.sql.Connection;  
    4. import java.sql.DriverManager;  
    5. import java.sql.ResultSet;  
    6. import java.sql.Statement;  
    7.   
    8.   
    9. public class FirstJDBC {  
    10.       
    11.     public static void main(String[] args)  
    12.     {  
    13.         //调用连接数据库的操作  
    14.         Connection con = createConnection();      
    15.           
    16.                   
    17.     }  
    18.       
    19.     /** 
    20.      * JDBC 建立 SQL Server数据库连接 
    21.      */  
    22.     private static Connection createConnection() {  
    23.           
    24.         //定义加载驱动程序  
    25.         String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";  
    26.           
    27.         //定义 连接 服务器 和 数据库sample  
    28.         String dbURL = "jdbc:sqlserver://localhost:1433; DataBaseName = sample1" ;  
    29.       
    30.         //默认用户名,不要用windows默认身份验证  
    31.         String userName = "sa" ;   
    32.         String userPassword = "zhichao" ;  
    33.         Connection connection = null ;  
    34.         Statement sta = null ;  
    35.           
    36.         try {  
    37.             //正式加载驱动  
    38.             Class.forName(driverName);  
    39.             //开始连接  
    40.             connection = DriverManager.getConnection(dbURL, userName, userPassword);  
    41.             System.out.println("Connection Success !");  
    42.               
    43.             //向数据库中执行SQL语句  
    44.             sta = connection.createStatement() ;  
    45.             ResultSet rs = sta.executeQuery("SELECT id,name,height From Table_1");  
    46.             while(rs.next())  
    47.             {  
    48.                 int id = rs.getInt("id");  
    49.                 String name = rs.getString("name");  
    50.                 float height = rs.getFloat("height");  
    51.                   
    52.                 System.out.println("id = "+id+" name = "+name+" height = "+height);  
    53.             }  
    54.           
    55.         } catch (Exception e) {  
    56.               
    57.             System.out.println("Connection Fail !");  
    58.             e.printStackTrace() ;  
    59.         }  
    60.           
    61.         /** 
    62.          * 关闭数据库 
    63.          * @param connection 
    64.          */  
    65.         finally  
    66.         {  
    67.             try {  
    68.                   
    69.                 if (null != sta)  
    70.                 {  
    71.                     sta.close() ;  
    72.                     sta = null;  
    73.                     System.out.println("Statement 关闭成功");  
    74.                 }  
    75.                   
    76.                 if (null != connection)  
    77.                 {  
    78.                     connection.close() ;  
    79.                     connection = null;  
    80.                     System.out.println("Connection 关闭成功");  
    81.                 }  
    82.                   
    83.             } catch (Exception e) {  
    84.                   
    85.                 e.printStackTrace() ;  
    86.             }         
    87.               
    88.         }         
    89.         return connection ;  
    90.     }  
    91. }  

    小结:

        要写一个jdbc程序,先要加载相应数据库的驱动程序,驱动程序最好放在你建的工程里面,可以在你的工程下面建一个 lib文件夹以存储外部的jar文件,这样的话把你的工程拷贝到别的计算机运行,仍能成功执行。

    jdbc代码一般步骤:

    1)加载外部驱动程序(jar包)

    2)正式加载驱动程序 (Class.forName(driverName) )

    3)获取connection连接 (在jdk中的sql包中,只提供了一个类那就是DriverManeger,通过调用它的静态方法getConnection(),可以得到以数据库的连接

    4)创建sql语句的声明(Statement),执行sql语句(查询),遍历结果集

    5)关闭数据库连接(一般用finally{}来处理,或者调用方法的形式来完成,关闭之前先判断你要关闭的对象连接是否为空,如果空那会抛异常,所以先判断)

    ------------------------------------- ------------------------------------- ------------------------Data Access Objects-------------------- ------------------------------------------- ---------------------------

    使用 DAO模式 来对数据库做增删改查操作

    这种模式可以大概分为三个层:1.DAO层  2.服务层  3.表现层

    1)表现层 :相当于客户端用来查看,提交信息的角色

    2)服务层 :是表现层和DAO层的纽带,其实也没干什么事就是通知消息的角色

    3)DAO   :真正要做事的角色(对数据库的某些操作)

    举个生活中的例子:

    就好比你去餐厅吃饭,你充当一个 (表现层)的角色,然后有美女服务员(服务层),问你需要吃什么东西,给你下一张订单,让你填。之后服务员把订单传到 厨师(DAO层)那里,具体操作厨师会搞定,一段时间后厨师把做好的食物传给服务员,服务员把食物在传给客户,这些操作就算基本完成了。

    执行顺序: 表现层-->服务层-->DAO层-->返回服务层-->返回表现层

    来看看实现DAO模式的UML图:

    代码实现:

    1.Bean文件,在这主要作用(有点像中介存储的角色):当从数据库拿出数据后,一个个set到该类里,进行赋值,然后把该对象放到集合中,之后再get出来

    Student.java

    [java] view plain copy
     
    1. package com.myjdbc.bean;  
    2.   
    3. public class Student {  
    4.       
    5.     private Integer stuId;  
    6.     private String stuName ;  
    7.     private Integer stuAge;  
    8.     private String stuTel ;  
    9.     private String stuAddress ;  
    10.     private Integer groupId;  
    11.       
    12.     public Integer getStuId() {  
    13.         return stuId;  
    14.     }  
    15.     public void setStuId(Integer stuId) {  
    16.         this.stuId = stuId;  
    17.     }  
    18.     public String getStuName() {  
    19.         return stuName;  
    20.     }  
    21.     public void setStuName(String stuName) {  
    22.         this.stuName = stuName;  
    23.     }  
    24.     public Integer getStuAge() {  
    25.         return stuAge;  
    26.     }  
    27.     public void setStuAge(Integer stuAge) {  
    28.         this.stuAge = stuAge;  
    29.     }  
    30.     public String getStuTel() {  
    31.         return stuTel;  
    32.     }  
    33.     public void setStuTel(String stuTel) {  
    34.         this.stuTel = stuTel;  
    35.     }  
    36.     public String getStuAddress() {  
    37.         return stuAddress;  
    38.     }  
    39.     public void setStuAddress(String stuAddress) {  
    40.         this.stuAddress = stuAddress;  
    41.     }  
    42.     public Integer getGroupId() {  
    43.         return groupId;  
    44.     }  
    45.     public void setGroupId(Integer groupId) {  
    46.         this.groupId = groupId;  
    47.     }  
    48.           
    49. }  


    2.java连接数据库的基本操作及关闭,封装在一个类中

    JDBCUtils.java

    [java] view plain copy
     
    1. package com.myjdbc.utils;  
    2.   
    3. import java.sql.Connection;  
    4. import java.sql.DriverManager;  
    5. import java.sql.ResultSet;  
    6. import java.sql.Statement;  
    7.   
    8. public class JDBCUtils {  
    9.     /** 
    10.      * 获取连接 
    11.      *  
    12.      */  
    13.     public static Connection getConnection()  
    14.     {  
    15.         String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";  
    16.   
    17.         String url = "jdbc:sqlserver://localhost:1433; DataBaseName = studentManager";  
    18.         String user = "sa" ;  
    19.         String password = "zhichao";  
    20.         Connection con = null ;  
    21.         try {  
    22.               
    23.             Class.forName(driverName);  
    24.             con = DriverManager.getConnection(url, user, password);  
    25.             System.out.println("success");  
    26.         } catch (Exception e) {  
    27.             e.printStackTrace();  
    28.         }  
    29.           
    30.         return con ;  
    31.           
    32.     }  
    33.       
    34.     /** 
    35.      * 关闭连接 
    36.      */  
    37.     public static void free(ResultSet rs, Statement sta , Connection con)  
    38.     {  
    39.         try {  
    40.             if(null != rs)  
    41.             {  
    42.                 rs.close();  
    43.                 rs = null ;  
    44.             }  
    45.               
    46.             if(null != sta)  
    47.             {  
    48.                 sta.close();  
    49.                 sta = null ;  
    50.             }  
    51.               
    52.             if(null != con)  
    53.             {  
    54.                 con.close();  
    55.                 con = null ;  
    56.             }  
    57.               
    58.         } catch (Exception e) {  
    59.             e.printStackTrace();  
    60.         }  
    61.     }  
    62. }  


     

    3.定义一个DAO接口

    StudentDAO.java

    [java] view plain copy
     
    1. package com.myjdbc.dao;  
    2.   
    3. import java.util.Set;  
    4.   
    5. import com.myjdbc.bean.Student ;  
    6.   
    7. public interface StudentDAO {  
    8.       
    9.     public int addStudent(Student student) ;  
    10.       
    11.     public int deleteStudent(String name);  
    12.       
    13.     public int updateStudent(String name);  
    14.       
    15.     public Student findStudent(String name);  
    16.       
    17.     public Set<Student> findAll();  
    18.   
    19.       
    20.       
    21.       
    22.       
    23.   
    24. }  


    4.实现DAO接口的类,具体DAO,做重要工作的类

    ConcreteStudentDao.java

    [java] view plain copy
     
    1. package com.myjdbc.dao;  
    2.   
    3. import java.sql.Connection;  
    4. import java.sql.PreparedStatement;  
    5. import java.sql.ResultSet;  
    6. import java.sql.SQLException;  
    7. import java.util.HashSet;  
    8. import java.util.Set;  
    9.   
    10. import com.myjdbc.bean.Student;  
    11. import com.myjdbc.dao.StudentDAO;  
    12. import com.myjdbc.utils.JDBCUtils;  
    13.   
    14. public class ConcreteStudentDao implements StudentDAO{  
    15.       
    16.     //增加一个学生  
    17.     public int addStudent(Student student)  
    18.     {  
    19.         Connection con = null ;  
    20.         PreparedStatement ps = null ;  
    21.         int i = 0 ;  
    22.         try  
    23.         {  
    24.             con = JDBCUtils.getConnection();  
    25.             String sql = "insert into student(stuName,stuAge,stuTel,stuAddress,groupId) values(?,?,?,?,?)";  
    26.             ps = con.prepareStatement(sql);  
    27.               
    28.             ps.setString(1, student.getStuName());  
    29.             ps.setInt(2, student.getStuAge());  
    30.             ps.setString(3, student.getStuTel());  
    31.             ps.setString(4, student.getStuAddress());  
    32.             ps.setInt(5, student.getGroupId());  
    33.               
    34.             i = ps.executeUpdate() ;  
    35.               
    36.         }  
    37.         catch(SQLException e)  
    38.         {  
    39.             throw new DAOException(e.getMessage(),e);  
    40.         }  
    41.         finally  
    42.         {  
    43.             JDBCUtils.free(null, ps, con);  
    44.         }  
    45.         return i;  
    46.     }  
    47.       
    48.     //删除一个学生  
    49.     public int deleteStudent(String name)  
    50.     {  
    51.         Connection con = null ;  
    52.         PreparedStatement ps = null ;  
    53.         int i = 0 ;  
    54.         try  
    55.         {  
    56.             con = JDBCUtils.getConnection();  
    57.             String sql = "delete from student where stuName =?";  
    58.             ps = con.prepareStatement(sql);  
    59.             ps.setString(1, name);  
    60.               
    61.             i = ps.executeUpdate() ;  
    62.               
    63.         }  
    64.         catch(SQLException e)  
    65.         {  
    66.             throw new DAOException(e.getMessage(),e);  
    67.         }  
    68.         finally  
    69.         {  
    70.             JDBCUtils.free(null, ps, con);  
    71.         }  
    72.               
    73.         return i;  
    74.     }  
    75.       
    76.     //修改一个学生  
    77.     public int updateStudent(String name)  
    78.     {  
    79.         Connection con = null ;  
    80.         PreparedStatement ps = null ;  
    81.         int i = 0 ;  
    82.         try  
    83.         {  
    84.             con = JDBCUtils.getConnection();  
    85.             String sql = "update student set stuAge=stuAge+1  where stuName =?";  
    86.             ps = con.prepareStatement(sql);  
    87.             ps.setString(1, name);  
    88.               
    89.             i = ps.executeUpdate() ;  
    90.               
    91.         }  
    92.         catch(SQLException e)  
    93.         {  
    94.             throw new DAOException(e.getMessage(),e);  
    95.         }  
    96.         finally  
    97.         {  
    98.             JDBCUtils.free(null, ps, con);  
    99.         }  
    100.           
    101.         return i;  
    102.     }  
    103.     //查询一行  
    104.     public Student findStudent(String name)  
    105.     {  
    106.         Connection con = null ;  
    107.         PreparedStatement ps = null ;  
    108.         Student stu = null ;  
    109.         ResultSet rs = null;  
    110.         try  
    111.         {  
    112.             con = JDBCUtils.getConnection();  
    113.             String sql = "select stuName,stuAge,stuTel,stuAddress,groupId from student where stuName =?";  
    114.             ps = con.prepareStatement(sql);  
    115.             ps.setString(1, name);  
    116.               
    117.             rs = ps.executeQuery() ;  
    118.             stu = new Student();  
    119.             while(rs.next())  
    120.             {  
    121.                 stu.setStuName(rs.getString(1));  
    122.                 stu.setStuAge(rs.getInt(2));  
    123.                 stu.setStuTel(rs.getString(3));  
    124.                 stu.setStuAddress(rs.getString(4));  
    125.                 stu.setGroupId(rs.getInt(5));  
    126.             }  
    127.               
    128.         }  
    129.         catch(SQLException e)  
    130.         {  
    131.             throw new DAOException(e.getMessage(),e);  
    132.         }  
    133.         finally  
    134.         {  
    135.             JDBCUtils.free(rs, ps, con);  
    136.         }  
    137.           
    138.         return stu;  
    139.     }  
    140.       
    141.     //查询所有  
    142.     public Set<Student> findAll()  
    143.     {  
    144.         Connection con = null ;  
    145.         PreparedStatement ps = null ;  
    146.         Student stu = null ;  
    147.         ResultSet rs = null;  
    148.         Set<Student> set = null ;  
    149.         try  
    150.         {  
    151.             con = JDBCUtils.getConnection();  
    152.             String sql = "select stuName,stuAge,stuTel,stuAddress,groupId from student";  
    153.             ps = con.prepareStatement(sql);  
    154.               
    155.             set = new HashSet<Student>() ;  
    156.             rs = ps.executeQuery() ;  
    157.               
    158.             while(rs.next())  
    159.             {  
    160.                 stu = new Student();  
    161.                   
    162.                 stu.setStuName(rs.getString(1));  
    163.                 stu.setStuAge(rs.getInt(2));  
    164.                 stu.setStuTel(rs.getString(3));  
    165.                 stu.setStuAddress(rs.getString(4));  
    166.                 stu.setGroupId(rs.getInt(5));  
    167.                   
    168.                 set.add(stu);  
    169.             }  
    170.               
    171.         }  
    172.         catch(SQLException e)  
    173.         {  
    174.             throw new DAOException(e.getMessage(),e);  
    175.         }  
    176.         finally  
    177.         {  
    178.             JDBCUtils.free(rs, ps, con);  
    179.         }  
    180.           
    181.         return set;  
    182.     }  
    183.          
    184. }  


    5.自定义异常 继承了运行时异常,具体操作让父类实现

    DAOException.java

    [java] view plain copy
     
    1. package com.myjdbc.dao;  
    2.   
    3. /** 
    4.  * 自定义异常 
    5.  * @author Administrator 
    6.  * 
    7.  */  
    8. public class DAOException extends RuntimeException {  
    9.       
    10.       
    11.     public DAOException()  
    12.     {  
    13.         super();  
    14.     }  
    15.       
    16.     public DAOException(String messege,Throwable cause)  
    17.     {  
    18.         super(messege,cause);  
    19.     }  
    20.       
    21.     public DAOException(String messege)  
    22.     {  
    23.         super(messege);  
    24.     }  
    25.       
    26.     public DAOException(Throwable cause)  
    27.     {  
    28.         super(cause);  
    29.     }  
    30.       
    31.       
    32.   
    33. }  


     

    6定义一个服务类(服务层),本来还要定义一个接口,这里简写了,客户与DAO的纽带,持有DAO对象的引用

    StudentService.java

    [java] view plain copy
     
    1. package com.myjdbc.service;  
    2.   
    3. import java.util.Set;  
    4.   
    5. import com.myjdbc.bean.Student;  
    6. import com.myjdbc.dao.StudentDAO;  
    7. import com.myjdbc.dao.ConcreteStudentDao;  
    8.   
    9. public class StudentService {  
    10.       
    11.     StudentDAO sd = new ConcreteStudentDao();  
    12.       
    13.     public int add(Student student)  
    14.     {  
    15.         return this.sd.addStudent(student);  
    16.     }  
    17.       
    18.     public int delete(String name)  
    19.     {  
    20.         return this.sd.deleteStudent(name);  
    21.     }  
    22.       
    23.     public int update(String name)  
    24.     {  
    25.         return this.sd.updateStudent(name);  
    26.     }  
    27.       
    28.     public Student find(String name)  
    29.     {  
    30.         return this.sd.findStudent(name);  
    31.     }  
    32.       
    33.     public Set<Student> findAll()  
    34.     {  
    35.         return this.sd.findAll();  
    36.     }  
    37.   
    38. }  


    7.定义一个测试类,相当于 (表现层)

    Client.java

    [java] view plain copy
     
      1. package com.myjdbc.test;  
      2.   
      3. import java.util.HashSet;  
      4. import java.util.Iterator;  
      5. import java.util.Set;  
      6.   
      7. import com.myjdbc.bean.Student;  
      8. import com.myjdbc.service.StudentService;  
      9.   
      10. public class Client {  
      11.    public static void main(String[] args)  
      12.    {  
      13.        Student stu = new Student();  
      14.        Set<Student> set = new HashSet<Student>();  
      15. //     stu.setStuName("zhangsan");  
      16. //     stu.setStuAge(20);  
      17. //     stu.setStuTel("18779157911");  
      18. //     stu.setStuAddress("china");  
      19. //     stu.setGroupId(1);  
      20.        StudentService ss = new StudentService();  
      21.        //System.out.println(ss.add(stu));  
      22.        //System.out.println(ss.delete("aa"));  
      23.        //System.out.println(ss.update("bb"));  
      24.        //stu = ss.find("cc");  
      25.        //System.out.println(stu.getStuName() +" " +stu.getStuAge()+" "+stu.getStuTel()+" "+stu.getStuAddress()+" "+stu.getGroupId());  
      26.        set = ss.findAll() ;  
      27.        Iterator<Student> iterator = set.iterator();  
      28.        while(iterator.hasNext())  
      29.        {  
      30.           Student student =  (Student)iterator.next() ;  
      31.           System.out.println(student.getStuName() +" " +student.getStuAge()+" "+student.getStuTel()+" "+student.getStuAddress()+" "+student.getGroupId());  
      32.        }  
      33.    }  
  • 相关阅读:
    让delphi2010能有delphi7的版面布局
    多线程的基本概念和Delphi线程对象Tthread介绍
    Delphi编写后台监控软件
    delphi 2010是动画GIF的支持方法
    delphi 资源文件详解
    delphi 基础之四 delphi 组织结构
    delphi 基础之三 编写和调用dll文件
    delphi 基础之三 文件流操作
    mysql (5.7版本)---的配置
    session--保持登录20分钟,常用与用户登录状态
  • 原文地址:https://www.cnblogs.com/Bighua123/p/7568647.html
Copyright © 2011-2022 走看看