• java面向对象 7


    一、什么是JDBC?

                       java中连接数据库的一种技术

    是java各种应用程序和数据库之间的桥梁

    由一组使用java语言编写的类和接口组成

    二、JDBC中常用的API?

      DriverManager类:管理不同数据库的jdbc驱动

     Connection接口:负责连接数据库并担任传递数据的任务

     Statement接口:由Connection产生,负责执行sql语句

      PreparedStatement是Statement的子接口

      除了具备父接口Statement的能力外,还具有4高(安全性、性能、可读性、可维护性)功能

      ResultSet接口:负责保存和处理Statement返回的查询结果

    三、使用JDBC如何连接sqlserver数据库?

             1、加载驱动

                                编码前的准备工作

      1.将sqljdbc2008.jar文件复制粘贴到项目的文件夹中

      2.将项目和jdbc驱动关联

    编码,加载驱动

                       Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);//处理异常try…catch

    2、编写数据库连接字符串、设置登录名、密码

                       2.1   final String url = ”jdbc:sqlserver://localhost:1433;

    databasename=存在的数据库名”;

                       2.2   final String name = ”sqlserver身份验证的登录名”;

                       2.3   final String pwd = ”登录名对应的密码”;

     1 public class BaseDAO {
     2     private Connection con=null;
     3     private PreparedStatement pre=null;
     4     private ResultSet re=null;
     5     
     6         //驱动路径
     7         private final String qd=
     8                 "com.microsoft.sqlserver.jdbc.SQLServerDriver";
     9         //数据库连接字符串
    10         private final String url = "jdbc:sqlserver://localhost:1433;"
    11                 + "databasename=epet2";
    12         private final String user = "sa";//登录名
    13         private final String password = "sasa";//密码
    14         
    15         //加载路径建立链接
    16         public void openDB(){
    17             try {
    18                 Class.forName(qd);
    19                 con=DriverManager.getConnection(url,user,password);
    20             } catch (ClassNotFoundException e) {
    21                 // TODO Auto-generated catch block
    22                 e.printStackTrace();
    23             } catch (SQLException e) {
    24                 // TODO Auto-generated catch block
    25                 e.printStackTrace();
    26             }
    27         }
    28         }
    JDBC

    3、使用DriverManger类的getConnection()方法,

    关联url、name、pwd,返回一个Connection接口

              Connection conn=DriverManger.getConnection(url,name,pwd);

    四、使用Statement接口对表的数据执行[增、删、改]操作

    1、加载驱动连接数据库

    2、  在try…catch外面,声明Statement变量并赋初值null

                       (或用PreparedStatement代替Statement

    3、  定义变量,保存sql语句(insert、delete、update语句)

    使用PreparedStatement接口,sql语句中values()中的值,使用?

    4、  DriverManager.getConnection()的下一行编写代码

    Statement变量=Connection变量.createStatement();

    PreparedStatement变量= Connection变量. prepareStatement(sql);

    5、调用Statement变量的executeUpdate(sql)执行sql语句

                                int rows=executeUpdate(sql);//返回受影响的行数

    sql语句中的?赋值

                      PreparedStatement变量.set数据类型(数字,值);

    调用PreparedStatement变量的executeUpdate()执行sql语句

                       int rows=executeUpdate();//返回受影响的行数

     

    6、根据受影响的行数,判断sql语句执行是否成功

    7、释放相关的资源

    finally{

                        try{

                                if(Statement变量或PreparedStatement变量!=null)

                                         Statement变量(或PreparedStatement变量).close();

                                if(Connection变量!=null)

                                        Connection变量.close();

                        }catch(SQLException e){

                                e.printStackTrace();

                        }

    五、使用JDBC查询表中的数据(ResultSet接口)

    1、加载sql2008 jdbc驱动包

    (自动添加try…catch,手动添加finally语句块

    用于释放资源)

    1、  在try…catch…finally语句块的外面,

    a)         声明3个接口(Connection、Statement或PreparedStatement、ResultSet的变量且赋值null

    b)         在finally块中,调用这3个接口的close()释放资源

    2、  编写数据库连接字符串url

    3、  使用DriverManager.getConnection(url,”登录名”,”登录密码”);

    获取Connection接口的对象

    4、  编写sql查询语句,保存到字符串的变量中

    5、  获取发送并执行sql查询语句的接口对象

    a)         父接口Statement对象

    Connection接口变量.createStatement();

    b)         子接口PreparedStatement对象

    Connection接口变量. prepareStatement(sql);

    6、  调用Statement或PreparedStatement接口的方法,

    执行sql查询语句,返回ResultSet

    a)                  父接口Statement对象

    ResultSet变量=Statement接口变量.executeQuery(sql);

    b)         子接口PreparedStatement对象

    ResultSet变量=Statement接口变量.executeQuery();

    7、  使用while循环,调用ResultSet接口变量的

    get数据类型(数字或列名)方法,来获取表中列的值

    while(ResultSet接口变量.next()){

               ResultSet接口变量.get数据类型(数字或列名);

                        get数据类型(数字);//数字从1开始

                        get数据类型(“列名”);

    }

     1  public int changData(String sql,ArrayList list){
     2             openDB();
     3             int r=0;
     4             try {
     5                 pre = con.prepareStatement(sql);
     6                 if(list!=null){//说明sql语句中有?参数
     7                     //使用循环,为sql语句中的?参数赋值
     8                     for(int i=0;i<list.size();i++){
     9                         pre.setObject(i+1, list.get(i));
    10                     }                    
    11                 }
    12                 r=pre.executeUpdate();
    13             } catch (SQLException e) {
    14                 e.printStackTrace();
    15             }
    16             finally{
    17                 close();//2、关闭数据库,释放相关的资源
    18             }
    19             return r;
    20         }
    21         
    22         //关闭数据,释放相关资源
    23         public void close(){
    24             try {
    25                 if(re!=null){
    26                     re.close();
    27                 }
    28                 if(pre!=null){
    29                     pre.close();
    30                 }
    31                 if(con!=null){
    32                     con.close();
    33                 }
    34             }catch (SQLException e) {
    35                 // TODO Auto-generated catch block
    36                 e.printStackTrace();
    37             }
    38         }
    39         
    40         //实现查询的方法
    41         public ResultSet inquiry(String sql,ArrayList list){
    42             openDB();
    43             try {
    44                 pre=con.prepareStatement(sql);
    45                 if(list!=null){//说明sql语句中有?参数
    46                     //使用循环,为sql语句中的?参数赋值
    47                     for(int i=0;i<list.size();i++){
    48                         pre.setObject(i+1, list.get(i));
    49                     }
    50                 }
    51                 re=pre.executeQuery();
    52             } catch (SQLException e) {
    53                 // TODO Auto-generated catch block
    54                 e.printStackTrace();
    55             } 
    56             return re;
    57         }
    58         
    59         //检查是否含有正确id
    60         public int checkPetId(int id){
    61             int r=0;
    62             String sql="select count(*) from pet where id=?";
    63             ArrayList list=new ArrayList();
    64             list.add(id);
    65             ResultSet re=inquiry(sql, list);
    66             
    67                 try {
    68                     while(re.next()){
    69                         r=re.getInt(1);
    70                     }
    71                 } catch (SQLException e) {
    72                     // TODO Auto-generated catch block
    73                     e.printStackTrace();
    74                 }
    75             return r;
    76         }
    77 }
    增加 删除 查找

    //示例代码

    BaseDao
    1 public interface CarDao {
    2     public int newCar(Car c); 
    3 }
    接口
     1 public class Car implements Serializable{
     2     private static final long SerialVersionUID=2070056025956126480L;
     3     private String userid;
     4     private String carno;
     5     private int price;
     6     private int discountprice;
     7     private int purchasetax;
     8     
     9     public Car(String userid,String carno,int price2,int discountprice2,int money2){
    10         this.userid=userid;
    11 
    12         this.carno=carno;
    13 
    14         this.price=price2;
    15         this.discountprice=discountprice2;
    16         this.purchasetax=money2;
    17         
    18     }
    19 
    20     public String getUserid() {
    21         return userid;
    22     }
    23 
    24     public String getCarno() {
    25         return carno;
    26     }
    27 
    28     public int getPrice() {
    29         return price;
    30     }
    31 
    32     public int getDiscountprice() {
    33         return discountprice;
    34     }
    35 
    36     public int getPurchasetax() {
    37         return purchasetax;
    38     }
    39 
    40     
    41 }
    实现接口的类
     1 public class CarDaoImpl extends BaseDao implements CarDao {
     2 
     3     @Override
     4     public int newCar(Car c) {
     5         int r=0;
     6         String sql="insert into car(userId,  carno,  price, discountprice, purchasetax)values(?,?,?,?,?)";
     7         ArrayList list=new ArrayList();
     8         list.add(c.getUserid());
     9         list.add(c.getCarno());
    10         list.add(c.getPrice());
    11         list.add(c.getDiscountprice());
    12         list.add(c.getPurchasetax());
    13         r=super.changData(sql, list);
    14         return r;
    15     }
    16 
    17 }
    实现类
  • 相关阅读:
    如何构建积木式Web应用
    ASP.NET 2.0 异步页面原理浅析 [1] [原]
    HybridDictionary 类
    datagrid自定义
    认识.NET的集合
    织梦 10060
    java.io.FileNotFoundException: E:\temp (拒绝访问。)
    引用与对象实例化
    C#中为DataGrid添加下拉列表框
    C#中使用指针
  • 原文地址:https://www.cnblogs.com/alhy/p/7017639.html
Copyright © 2020-2023  润新知