java面向对象第八章

一、什么是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 = ”登录名对应的密码”;

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

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

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

public class BaseDAO {
    private Connection con=null;
    private PreparedStatement pre=null;
    private ResultSet re=null;
    
        //驱动路径
        private final String qd=
                "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        //数据库连接字符串
        private final String url = "jdbc:sqlserver://localhost:1433;"
                + "databasename=epet2";
        private final String user = "sa";//登录名
        private final String password = "sasa";//密码
        
        //加载路径建立链接
        public void openDB(){
            try {
                Class.forName(qd);
                con=DriverManager.getConnection(url,user,password);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        }
JDBC

四、使用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();

                        }

public class BaseDAO {
    private Connection con=null;
    private PreparedStatement pre=null;
    private ResultSet re=null;
    
        //驱动路径
        private final String qd=
                "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        //数据库连接字符串
        private final String url = "jdbc:sqlserver://localhost:1433;"
                + "databasename=epet2";
        private final String user = "sa";//登录名
        private final String password = "sasa";//密码
        
        //加载路径建立链接
        public void openDB(){
            try {
                Class.forName(qd);
                con=DriverManager.getConnection(url,user,password);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        //实现增删改功能
        public int changData(String sql,ArrayList list){
            openDB();
            int r=0;
            try {
                pre = con.prepareStatement(sql);
                if(list!=null){//说明sql语句中有?参数
                    //使用循环,为sql语句中的?参数赋值
                    for(int i=0;i<list.size();i++){
                        pre.setObject(i+1, list.get(i));
                    }                    
                }
                r=pre.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            finally{
                close();//2、关闭数据库,释放相关的资源
            }
            return r;
        }
        
        //关闭数据,释放相关资源
        public void close(){
            try {
                if(re!=null){
                    re.close();
                }
                if(pre!=null){
                    pre.close();
                }
                if(con!=null){
                    con.close();
                }
            }catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        //实现查询的方法
        public ResultSet inquiry(String sql,ArrayList list){
            openDB();
            try {
                pre=con.prepareStatement(sql);
                if(list!=null){//说明sql语句中有?参数
                    //使用循环,为sql语句中的?参数赋值
                    for(int i=0;i<list.size();i++){
                        pre.setObject(i+1, list.get(i));
                    }
                }
                re=pre.executeQuery();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            return re;
        }
        
        //检查是否含有正确id
        public int checkPetId(int id){
            int r=0;
            String sql="select count(*) from pet where id=?";
            ArrayList list=new ArrayList();
            list.add(id);
            ResultSet re=inquiry(sql, list);
            
                try {
                    while(re.next()){
                        r=re.getInt(1);
                    }
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            return r;
        }
}
BaseDao

五、使用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);

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

执行sql查询语句,返回ResultSet

a)                    父接口Statement对象

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

b)         子接口PreparedStatement对象

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

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

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

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

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

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

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

}

public class BaseDao {
    private Connection con=null;
    private PreparedStatement pre=null;
    private ResultSet re=null;
    
        //驱动路径
        private final String qd=
                "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        //数据库连接字符串
        private final String url = "jdbc:sqlserver://localhost:1433;"
                + "databasename=epet2";
        private final String user = "sa";//登录名
        private final String password = "sasa";//密码
        
        //加载路径建立链接
        public void openDB(){
            try {
                Class.forName(qd);
                con=DriverManager.getConnection(url,user,password);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        //实现增删改功能
                public int changData(String sql,ArrayList list){
                    openDB();
                    int r=0;
                    try {
                        pre = con.prepareStatement(sql);
                        if(list!=null){//说明sql语句中有?参数
                            //使用循环,为sql语句中的?参数赋值
                            for(int i=0;i<list.size();i++){
                                pre.setObject(i+1, list.get(i));
                            }                    
                        }
                        r=pre.executeUpdate();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    finally{
                        close();//2、关闭数据库,释放相关的资源
                    }
                    return r;
                }
                
                //关闭数据,释放相关资源
                public void close(){
                    try {
                        if(re!=null){
                            re.close();
                        }
                        if(pre!=null){
                            pre.close();
                        }
                        if(con!=null){
                            con.close();
                        }
                    }catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
}
BaseDao
public interface CarDao {
    public int newCar(Car c); 
}
接口
public class Car implements Serializable{
    private static final long SerialVersionUID=2070056025956126480L;
    private String userid;
    private String carno;
    private int price;
    private int discountprice;
    private int purchasetax;
    
    public Car(String userid,String carno,int price2,int discountprice2,int money2){
        this.userid=userid;

        this.carno=carno;

        this.price=price2;
        this.discountprice=discountprice2;
        this.purchasetax=money2;
        
    }

    public String getUserid() {
        return userid;
    }

    public String getCarno() {
        return carno;
    }

    public int getPrice() {
        return price;
    }

    public int getDiscountprice() {
        return discountprice;
    }

    public int getPurchasetax() {
        return purchasetax;
    }

    
}
Car类
public class CarDaoImpl extends BaseDao implements CarDao {

    @Override
    public int newCar(Car c) {
        int r=0;
        String sql="insert into car(userId,  carno,  price, discountprice, purchasetax)values(?,?,?,?,?)";
        ArrayList list=new ArrayList();
        list.add(c.getUserid());
        list.add(c.getCarno());
        list.add(c.getPrice());
        list.add(c.getDiscountprice());
        list.add(c.getPurchasetax());
        r=super.changData(sql, list);
        return r;
    }

}
实体类
public static void main(String [] args){
        //计算车辆的购置税
        Scanner input=new Scanner(System.in);
        System.out.println("记录车辆购置税,请按提示录入相关信息:");
        System.out.print("请输入车主的身份证号码(18位):");
        String userId=input.next();
        
        System.out.print("请输入车辆的识别码(17位):");
        String carNo=input.next();
        
        System.out.print("请输入车辆的排放量:");
        double pai=input.nextDouble();
        
        System.out.print("请输入官方指导价:");
        int price=input.nextInt();
        
        System.out.print("请输入发票价格:");
        int discountprice=input.nextInt();
        
        //计税价格
        double money=discountprice/1.17;
        //车辆购置税
        double money2=0;
        //计算车辆购置税
        if(pai<=1.6){
            money2=money*0.075;
        }else{
            money2=money*0.1;
        }
        Car c=new Car(userId,carNo,price,discountprice,(int)money2);
        int r=CarManager.newCar(c);
        if(r>0){
        System.out.println("数据保存成功,车辆购置税为:"+(int)money2);
        }else{
            System.out.println("输入数据有误,数据保存失败!");
        }
    }
测试类

                       

原文地址:https://www.cnblogs.com/22joke/p/7009634.html