JavaSE学习总结(九)—— Java访问数据库(JDBC)

一、JDBC简介

JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。JDBC是用于java操作数据库,如完成数据库的连接,添加,修改,删除,查询等操作。

1.2、工作原理

JDBC API可做三件事:与数据库建立连接、执行SQL 语句、处理结果

DriverManager :依据数据库的不同,管理JDBC驱动

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

Statement :由 Connection 产生、负责执行SQL语句

ResultSet:负责保存Statement执行后所产生的查询结果集

1.3、简单示例

1.3.1、创建表与添加数据

#创建表
CREATE TABLE `stu` (
`id`  int NULL AUTO_INCREMENT ,
`name`  varchar(32) NOT NULL ,
`sex`  varchar(4) NULL ,
`age`  int NULL ,
PRIMARY KEY (`id`)
);

#删除表
drop table stu


#添加数据
insert into stu(name,sex,age) values('张学友','',18);
insert into stu(name,sex,age) values('张娜拉','',73);
insert into stu(name,sex,age) values('张家辉','',23);
insert into stu(name,sex,age) values('张汇美','',85);
insert into stu(name,sex,age) values('张铁林','',35);
insert into stu(name,sex,age) values('张国立','',99);

#2、查询数据-----

#2.1、查询所有学生
select id,name,sex,age from stu;

#2.2、查询年龄大于80岁女学生
select id,name,sex,age from stu where age>80 and sex='';

#2.3、查询平均年龄
select AVG(age) from stu where sex='';

#3、修改数据-----
#3.1、将编号为1的学生年龄加大1岁
update stu set age=age+1 where id=1;

#3.2、将80岁以上的女学生年龄修改为90岁且将姓名后增加“老人”
#CONCAT(str1,str2,...) 连接字符串
update stu set age=90,name=CONCAT(name,'(老人)') where age>=80 and sex='';

#3.3、将编号4的学生名字修改为张汇美
update stu set name='张汇美' where id=4;

#4、删除数据-----
#4.1、删除年龄大于70岁的学生
delete from stu where age>70;

#4.2、删除所有学生
delete from stu;
查看

1.3.2、添加引用

请查看第二大点

1.3.3、连接数据库并查询所有学生信息

package com.zhangguo.chapter11.demo1;

import java.sql.*;

public class StudentJDBC {
    
    //加载驱动
    static{
        try {
            //反射获得类型
            Class.forName( "com.mysql.jdbc.Driver" );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //连接对象
        Connection conn = null;
        try {
            //获得连接对象,school数据库名,root用户名,uchr@123密码
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "uchr@123" );
            System.out.println("连接成功");
            
            //查询所有学生信息,命令对象
            PreparedStatement cmd=conn.prepareStatement("select id,name,sex,age from stu");
            
            //执行查询并返回结果集
            ResultSet set=cmd.executeQuery();
            
            //遍历每一行
            while (set.next()) {
                //取出当前行的id值
                System.out.print(set.getInt("id")+"\t");
                System.out.print(set.getString("name")+"\t");
                System.out.print(set.getString("sex")+"\t");
                System.out.print(set.getInt("age")+"\n");
            }
            //关闭结果集
            set.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭连接
                conn.close();
                System.out.println("关闭成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 结果:

二、加载驱动

2.1、下载驱动 

https://www.mysql.com/products/connector/

 

 

 

 

2.2、在java应用程序中引入jar驱动包

 

 

    //加载驱动
    static{
        try {
            //反射获得类型
            Class.forName( "com.mysql.jdbc.Driver" );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

三、获取数据库连接

            //获得连接对象,school数据库名,root用户名,uchr@123密码
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8", "root", "uchr@123" );
            System.out.println("连接成功");

四、Java实现数据库访问

package com.zhangguo.chapter11.demo1;

import java.sql.*;

public class StudentJDBC {
    
    //加载驱动
    static{
        try {
            //反射获得类型
            Class.forName( "com.mysql.jdbc.Driver" );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //连接对象
        Connection conn = null;
        try {
            //获得连接对象,school数据库名,root用户名,uchr@123密码
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8", "root", "uchr@123" );
            System.out.println("连接成功");
            
            //查询所有学生信息,命令对象
            PreparedStatement cmd=conn.prepareStatement("select id,name,sex,age from stu");
            
            //执行查询并返回结果集
            ResultSet set=cmd.executeQuery();
            
            //遍历每一行
            while (set.next()) {
                //取出当前行的id值
                System.out.print(set.getInt("id")+"\t");
                System.out.print(set.getString("name")+"\t");
                System.out.print(set.getString("sex")+"\t");
                System.out.print(set.getInt("age")+"\n");
            }
            //关闭结果集
            set.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭连接
                conn.close();
                System.out.println("关闭成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

4.1、增删改

4.1.1、增加

package com.zhangguo.chapter11.demo1;

import java.sql.*;

public class StudentCRUD {
    
    //加载驱动
    static{
        try {
            //反射获得类型
            Class.forName( "com.mysql.jdbc.Driver" );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //连接对象
        Connection conn = null;
        try {
            //获得连接对象,school数据库名,root用户名,uchr@123密码
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8", "root", "uchr@123" );
            System.out.println("连接成功");
            
            //执行添加
            PreparedStatement cmd=conn.prepareStatement("insert into stu(name,sex,age) values('张卫健','男',45);");
            //执行操作并返回影响行数
            int n=cmd.executeUpdate();
            System.out.println("影响行数:"+n);
            //释放命令对象
            cmd.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭连接
                conn.close();
                System.out.println("关闭成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

4.1.2、更新

将id为8的name与sex修改

package com.zhangguo.chapter11.demo1;

import java.sql.*;

public class StudentUpdate {
    
    //加载驱动
    static{
        try {
            //反射获得类型
            Class.forName( "com.mysql.jdbc.Driver" );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //连接对象
        Connection conn = null;
        try {
            //获得连接对象,school数据库名,root用户名,uchr@123密码
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8", "root", "uchr@123" );
            System.out.println("连接成功");
            
            //执行更新
            PreparedStatement cmd=conn.prepareStatement("update stu set name='张一山',sex='男' where id=8");
            //执行操作并返回影响行数
            int n=cmd.executeUpdate();
            System.out.println("影响行数:"+n);
            //释放命令对象
            cmd.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭连接
                conn.close();
                System.out.println("关闭成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

结果:

4.1.3、删除

 

package com.zhangguo.chapter11.demo1;

import java.sql.*;

public class StudentDelete {
    
    //加载驱动
    static{
        try {
            //反射获得类型
            Class.forName( "com.mysql.jdbc.Driver" );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //连接对象
        Connection conn = null;
        try {
            //获得连接对象,school数据库名,root用户名,uchr@123密码
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8", "root", "uchr@123" );
            System.out.println("连接成功");
            
            //执行删除
            PreparedStatement cmd=conn.prepareStatement("delete from stu where id=8");
            //执行操作并返回影响行数
            int n=cmd.executeUpdate();
            System.out.println("影响行数:"+n);
            //释放命令对象
            cmd.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭连接
                conn.close();
                System.out.println("关闭成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

结果:

4.2、查询

4.2.1、查询结果集

#查询所有女生的姓名与年龄
select name,age from stu where sex='女'

package com.zhangguo.chapter11.demo1;

import java.sql.*;

public class StudentSelect {
    
    //加载驱动
    static{
        try {
            //反射获得类型
            Class.forName( "com.mysql.jdbc.Driver" );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //连接对象
        Connection conn = null;
        ResultSet resultset=null;
        PreparedStatement cmd=null;
        try {
            //获得连接对象,school数据库名,root用户名,uchr@123密码
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8", "root", "uchr@123" );
            System.out.println("连接成功");
            
            //查询所有女生的姓名与年龄
            cmd=conn.prepareStatement("select name,age from stu where sex='女'");
            //执行查询返回结果集
            resultset=cmd.executeQuery();
            //获取数据,遍历,指针下移
            while (resultset.next()) {
                System.out.println(resultset.getString("name")+"\t"+resultset.getInt("age"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //释放对象
                if(conn!=null)conn.close();
                if(cmd!=null)cmd.close();
                if(resultset!=null)resultset.close();
                System.out.println("关闭成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

4.2.2、查询单行单列数据

package com.zhangguo.chapter11.demo1;

import java.sql.*;

public class StudentSelect2 {
    
    //加载驱动
    static{
        try {
            //反射获得类型
            Class.forName( "com.mysql.jdbc.Driver" );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //连接对象
        Connection conn = null;
        ResultSet resultset=null;
        PreparedStatement cmd=null;
        try {
            //获得连接对象,school数据库名,root用户名,uchr@123密码
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8", "root", "uchr@123" );
            System.out.println("连接成功");
            
            //查询男生人数
            cmd=conn.prepareStatement("select count(*) from stu where sex='男'");
            //执行查询返回结果集
            resultset=cmd.executeQuery();
            //获取数据,遍历,指针下移
            if(resultset.next()) {
                //根据索引获取当前行的数据,1表示第几列
                System.out.println("男生数:"+resultset.getInt(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //释放对象
                if(conn!=null)conn.close();
                if(cmd!=null)cmd.close();
                if(resultset!=null)resultset.close();
                System.out.println("关闭成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

结果:

4.3、带参数

 sql语句中的字符如果来自用户,则可能会拼接sql,拼接字符串的做法很不安全,可以使用带参数的命令。

4.3.1、添加学员 - 拼接

package com.zhangguo.chapter11.demo1;

import java.sql.*;
import java.util.Scanner;

public class StudentParam1 {
    
    //加载驱动
    static{
        try {
            //反射获得类型
            Class.forName( "com.mysql.jdbc.Driver" );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //连接对象
        Connection conn = null;
        PreparedStatement cmd=null;
        try {
            //获得连接对象,school数据库名,root用户名,uchr@123密码
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8", "root", "uchr@123" );
            System.out.println("连接成功");
            
            Scanner input=new Scanner(System.in);
            System.out.print("请输入姓名:");
            String name=input.next();
            System.out.print("请输入性别:");
            String sex=input.next();
            System.out.print("请输入年龄:");
            int age=input.nextInt();
            
            //查询男生人数
            cmd=conn.prepareStatement("insert into stu(name,sex,age) values('");
            //执行添加
            int n=cmd.executeUpdate();
            System.out.println("影响行数:"+n);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //释放对象
                if(conn!=null)conn.close();
                if(cmd!=null)cmd.close();
                System.out.println("关闭成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 

4.3.2、添加学员 - 参数

package com.zhangguo.chapter11.demo1;

import java.sql.*;
import java.util.Scanner;

public class StudentParam2 {
    
    //加载驱动
    static{
        try {
            //反射获得类型
            Class.forName( "com.mysql.jdbc.Driver" );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //连接对象
        Connection conn = null;
        PreparedStatement cmd=null;
        try {
            //获得连接对象,school数据库名,root用户名,uchr@123密码
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8", "root", "uchr@123" );
            System.out.println("连接成功");
            
            Scanner input=new Scanner(System.in);
            System.out.print("请输入姓名:");
            String name=input.next();
            System.out.print("请输入性别:");
            String sex=input.next();
            System.out.print("请输入年龄:");
            int age=input.nextInt();
            
            //查询男生人数
            cmd=conn.prepareStatement("insert into stu(name,sex,age) values(?,?,?);");
            //指定参数
            cmd.setString(1, name);
            cmd.setString(2, sex);
            cmd.setInt(3, age);
            //执行添加
            int n=cmd.executeUpdate();
            System.out.println("影响行数:"+n);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //释放对象
                if(conn!=null)conn.close();
                if(cmd!=null)cmd.close();
                System.out.println("关闭成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 

 

4.4、封装

从前面的示例中可以看出如果数据库访问的代码(脚本)存在大量的冗余,操作模式基本相同,对数据库访问进行封装可以实现代码的可复用、可扩展、可维护

结合反射对JDBC的数据库访问封装如下:

学生实体类Stu.java:

package com.zhangguo.util.test;

/**
 * Java Bean (java 豆子)
 * 实体类
 * */
public class Stu {
    public Stu(int id, String name, String sex, int age) {
        super();
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public Stu(String name, String sex, int age) {
        super();
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
    
    public Stu() {
    }

    private int id;
    private String name;
    private String sex;
    private int age;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

 

JDBCUtils数据库访问封装

package com.zhangguo.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JDBCUtils {

    public static String DRIVER="com.mysql.jdbc.Driver";
    public static String URL="jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8";
    public static String USER_NAME="root";
    public static String PASSWORD="uchr@123";

    //加载驱动
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private JDBCUtils() {

    }

    /**
     * 获得连接
     * 
     * @return
     */
    public static Connection getconnnection() {
        Connection con = null;
        try {
            con = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    /**
     * 关闭连接
     * 
     * @param rs
     * @param st
     * @param con
     */
    public static void close(ResultSet rs, Statement st, Connection con) {
        try {
            try {
                if (rs != null) {
                    rs.close();
                }
            } finally {
                try {
                    if (st != null) {
                        st.close();
                    }
                } finally {
                    if (con != null)
                        con.close();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     * 
     * @param rs
     */
    public static void close(ResultSet rs) {
        Statement st = null;
        Connection con = null;
        try {
            try {
                if (rs != null) {
                    st = rs.getStatement();
                    rs.close();
                }
            } finally {
                try {
                    if (st != null) {
                        con = st.getConnection();
                        st.close();
                    }
                } finally {
                    if (con != null) {
                        con.close();
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     * 
     * @param st
     * @param con
     */
    public static void close(Statement st, Connection con) {
        try {
            try {
                if (st != null) {
                    st.close();
                }
            } finally {
                if (con != null)
                    con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * insert/update/delete
     * 增加/更新/删除
     * 
     * @param sql 数据库语句
     * @param args 可变参数(可以不带参数,可以带0-n个参数)
     * @return
     */
    public static int update(String sql, Object... args) {
        int result = 0;
        Connection con = getconnnection();
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    ps.setObject((i + 1), args[i]);
                }
            }
            result = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(ps, con);
        }

        return result;
    }

    /**
     * query, because need to manually close the resource, so not recommended
     * for use it
     * 
     * @param sql
     * @param args
     * @return ResultSet
     */
    @Deprecated  //注解
    public static ResultSet query(String sql, Object... args) {
        ResultSet result = null;
        Connection con = getconnnection();
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    ps.setObject((i + 1), args[i]);
                }
            }
            result = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Query a single record
     * 查询单个记录
     * @param sql
     * @param args
     * @return Map<String,Object>
     */
    public static Map<String, Object> queryForMap(String sql, Object... args) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map<String, Object>> list = queryForList(sql, args);
        if (list.size() > 0) {
            result = list.get(0);
        }
        return result;
    }

    /**
     * Query a single record
     * 查询单个记录返回强类型对象
     * @param sql
     * @param args
     * @return <T>  //泛型
     */
    public static <T> T queryForObject(String sql, Class<T> clz, Object... args) {
        T result = null;
        List<T> list = queryForList(sql, clz, args);
        if (list.size() > 0) {
            result = list.get(0);
        }
        return result;
    }

    /**
     * Query a single record
     * 
     * @param sql
     * @param args
     * @return List<Map<String,Object>>
     */
    public static List<Map<String, Object>> queryForList(String sql, Object... args) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        Connection con = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            con = getconnnection();
            ps = con.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    ps.setObject((i + 1), args[i]);
                }
            }
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<String, Object>();
                for (int i = 1; i <= columnCount; i++) {
                    map.put(rsmd.getColumnLabel(i), rs.getObject(i));
                }
                result.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(rs, ps, con);
        }
        return result;
    }

    /**
     * Query records
     * 查询多个对象,返回强类型集合
     * @param sql
     * @param args
     * @return List<T>
     */
    public static <T> List<T> queryForList(String sql, Class<T> clz, Object... args) {
        List<T> result = new ArrayList<T>();
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = getconnnection();
            ps = con.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    ps.setObject((i + 1), args[i]);
                }
            }
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                T obj = clz.newInstance();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = rsmd.getColumnName(i);
                    String methodName = "set" + columnName.substring(0, 1).toUpperCase()
                            + columnName.substring(1, columnName.length());
                    Method method[] = clz.getMethods();
                    for (Method meth : method) {
                        if (methodName.equals(meth.getName())) {
                            meth.invoke(obj, rs.getObject(i));
                        }
                    }
                }
                result.add(obj);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } finally {
            close(rs, ps, con);
        }
        return result;
    }
}

测试:

package com.zhangguo.util.test;

import java.util.List;

import com.zhangguo.util.JDBCUtils;

public class JDBCUtilTest {

    public static void main(String[] args) {
        //增加
        int n=JDBCUtils.update("insert into stu(name,sex,age) values(?,?,?)", "王娜菲","男",87);
        System.out.println("成功添加:"+n+"行");
        //修改
        JDBCUtils.update("update stu set name='李娜娜' where id=?",7);
        //删除
        JDBCUtils.update("delete from stu where id=?",10);
        //查询
        List<Stu> stus=JDBCUtils.queryForList("select id,name,age,sex from stu where age>? and name like ?", Stu.class,18,"%娜%");
        //遍历学生集合
        for (Stu stu : stus) {
            System.out.println(stu.getName()+"\t"+stu.getSex()+"\t"+stu.getAge());
        }
    }
}

运行结果:

五、DVD租赁系统JDBC版

5.1、数据库

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50506
Source Host           : localhost:3306
Source Database       : dvdstore

Target Server Type    : MYSQL
Target Server Version : 50506
File Encoding         : 65001

Date: 2017-06-08 11:31:13
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `dvd`
-- ----------------------------
DROP TABLE IF EXISTS `dvd`;
CREATE TABLE `dvd` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '编号',
  `name` varchar(64) NOT NULL COMMENT '名称',
  `price` double DEFAULT NULL COMMENT '价格',
  `isRent` int(11) DEFAULT NULL COMMENT '是否借出',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of dvd
-- ----------------------------
INSERT INTO `dvd` VALUES ('2', '异形', '75.3', '0');
INSERT INTO `dvd` VALUES ('3', '暗战', '19.5', '1');
INSERT INTO `dvd` VALUES ('4', '战狼', '9.98', '0');

5.2、实现类

 DVD.java

package com.zhangguo.dvd.v2;

/** 光碟 实体 模型 */
public class DVD {

    /** 构造方法 */
    public DVD(int _id, String _name, double _price, int _isRent) {
        this.id = _id;
        this.name = _name;
        this.price = _price;
        this.isRent = _isRent;
    }
    public DVD(String _name, double _price, int _isRent) {
        this.name = _name;
        this.price = _price;
        this.isRent = _isRent;
    }
    public DVD() {
    }

    /** 编号 */
    private int id;
    /** 名称 */
    private String name;
    /** 价格 */
    private double price;
    /** 是否被借出 0未借出 1借出 */
    private int isRent;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getIsRent() {
        return isRent;
    }

    public void setIsRent(int isRent) {
        this.isRent = isRent;
    }

    @Override
    public String toString() {
        return ("编号:" + this.id + "\t\t" + "名称:" + this.name + "\t\t" + "价格:" + this.price + "\t\t" + "借出:"
                + (this.isRent==1 ? "是" : "否"));
    }
}

DVDService.java

package com.zhangguo.dvd.v2;

import java.util.List;

/** DVD服务类,完成数据库访问 */
public class DVDService {

    /**添加DVD到数据库**/
    public int add(DVD dvd){
        return JDBCUtils.update("insert into dvd(name,price,isRent) values(?,?,?);", dvd.getName(),dvd.getPrice(),dvd.getIsRent());
    }
    
    /**删除DVD**/
    public int del(int id){
        return JDBCUtils.update("delete from dvd where id=?", id);
    }
    
    /**更新DVD到数据库**/
    public int update(DVD dvd){
        return JDBCUtils.update("update dvd set name=?,price=?,isRent=? where id=?", dvd.getName(),dvd.getPrice(),dvd.getIsRent(),dvd.getId());
    }
    
    /**获得所有DVD信息*/
    public List<DVD> getAll(){
        return JDBCUtils.queryForList("select id,name,price,isRent from dvd", DVD.class);
    }
    
    /**获得DVD信息通过状态*/
    public List<DVD> getAll(int isRent){
        return JDBCUtils.queryForList("select id,name,price,isRent from dvd where isRent=?", DVD.class,isRent);
    }
    
    /**根据DVD编号获得单个DVD*/
    public DVD get(int id){
        return JDBCUtils.queryForObject("select id,name,price,isRent from dvd where id=?", DVD.class, id);
    }
    
    /**根据DVD编号更新指定状态*/
    public int edit(int id,int isRent){
        return JDBCUtils.update("update dvd set isRent=? where id=?", isRent,id);
    }
    
}

DVDStore.java

package com.zhangguo.dvd.v2;

import java.util.List;
import java.util.Scanner;

public class DVDStore {

    /** 数据访问 */
    public DVDService service = new DVDService();
    /** 扫描器 */
    Scanner input = new Scanner(System.in);

    /** 菜单 */
    public void menu() {
        $("***************************DVD小店欢迎您***************************");
        $("1、显示DVD");
        $("2、借出DVD");
        $("3、归还DVD");
        $("4、添加DVD");
        $("5、删除DVD");
        $("6、编辑DVD");
        $("7、退出系统");
        $("***************************DVD小店欢迎您***************************");
        $$("请选择[1-7]:");
        int index = input.nextInt();
        switch (index) {
        case 1:
            fun1();
            break;
        case 2:
            fun2(1);
            break;
        case 3:
            fun3(0);
            break;
        case 4:
            fun4();
            break;
        case 5:
            fun5();
            break;
        case 6:
            fun6();
            break;
        case 7:
            fun7();
            break;
        default:
            $("输入有误,请重输");
            break;
        }
        menu();
    }

    /** 6、编辑DVD */
    private void fun6() {
        $$("编号:");
        int _id = input.nextInt();
        $$("名称:");
        String _name = input.next();
        $$("价格:");
        double _price = input.nextDouble();
        $$("借出[0/1]:");
        int _isRent = input.nextInt();

        DVD dvd = service.get(_id);
        if (_name != null && !_name.equals("")) {
            dvd.setName(_name);
        }
        if (_price > 0) {
            dvd.setPrice(_price);
        }
        if (_isRent >= 0) {
            dvd.setIsRent(_isRent);
        }

        int n = service.update(dvd);
        if (n > 0) {
            $("更新成功");
        } else {
            $("更新失败");
        }
    }

    /** 7、退出系统 */
    private void fun7() {
        $$("欢迎您下次光临!");
        System.exit(0);
    }

    /** 5、删除DVD */
    private void fun5() {
        if (fun1() > 0) {
            $$("请输入要删除的编号:");
            int id = input.nextInt();
            int n = service.del(id);
            if (n > 0) {
                $("删除成功");
            } else {
                $("删除失败");
            }
        } else {
            $("您的商店没有任何DVD,现在添加");
        }
    }

    /** 2、借出DVD */
    private void fun2(int isRent) {
        if (show(0) > 0) {
            $$("请输入要操作的编号:");
            int id = input.nextInt();
            int n = service.edit(id, isRent);
            if (n > 0) {
                $("操作成功");
            } else {
                $("操作失败");
            }
        } else {
            $("没有可以借出的DVD");
        }
    }

    /** 3、归还DVD */
    private void fun3(int isRent) {
        if (show(1) > 0) {
            $$("请输入要操作的编号:");
            int id = input.nextInt();
            int n = service.edit(id, isRent);
            if (n > 0) {
                $("操作成功");
            } else {
                $("操作失败");
            }
        } else {
            $("没有需要归还的DVD");
        }
    }

    /** 1、显示DVD */
    private int fun1() {
        List<DVD> dvds = service.getAll();
        for (DVD dvd : service.getAll()) {
            $(dvd);
        }
        return dvds.size();
    }

    /** 显示指定状态的DVD */
    private int show(int isRent) {
        List<DVD> dvds = service.getAll(isRent);
        for (DVD dvd : dvds) {
            $(dvd);
        }
        return dvds.size();
    }

    /** 4、添加DVD */
    private void fun4() {
        $$("名称:");
        String _name = input.next();
        $$("价格:");
        double _price = input.nextDouble();
        $$("借出[0/1]:");
        int _isRent = input.nextInt();
        service.add(new DVD(_name, _price, _isRent));
        $("添加成功");
    }

    /** 工具方法 */
    public void $(Object obj) {
        System.out.println(obj);
    }

    public void $$(Object obj) {
        System.out.print(obj);
    }
}

JDBCUtils.java

package com.zhangguo.dvd.v2;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JDBCUtils {

    public static String DRIVER="com.mysql.jdbc.Driver";
    public static String URL="jdbc:mysql://localhost:3306/dvdstore?useUnicode=true&characterEncoding=UTF-8";
    public static String USER_NAME="root";
    public static String PASSWORD="uchr@123";

    //加载驱动
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private JDBCUtils() {

    }

    /**
     * 获得连接
     * 
     * @return
     */
    public static Connection getconnnection() {
        Connection con = null;
        try {
            con = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    /**
     * 关闭连接
     * 
     * @param rs
     * @param st
     * @param con
     */
    public static void close(ResultSet rs, Statement st, Connection con) {
        try {
            try {
                if (rs != null) {
                    rs.close();
                }
            } finally {
                try {
                    if (st != null) {
                        st.close();
                    }
                } finally {
                    if (con != null)
                        con.close();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     * 
     * @param rs
     */
    public static void close(ResultSet rs) {
        Statement st = null;
        Connection con = null;
        try {
            try {
                if (rs != null) {
                    st = rs.getStatement();
                    rs.close();
                }
            } finally {
                try {
                    if (st != null) {
                        con = st.getConnection();
                        st.close();
                    }
                } finally {
                    if (con != null) {
                        con.close();
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     * 
     * @param st
     * @param con
     */
    public static void close(Statement st, Connection con) {
        try {
            try {
                if (st != null) {
                    st.close();
                }
            } finally {
                if (con != null)
                    con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * insert/update/delete
     * 增加/更新/删除
     * 
     * @param sql 数据库语句
     * @param args 可变参数(可以不带参数,可以带0-n个参数)
     * @return
     */
    public static int update(String sql, Object... args) {
        int result = 0;
        Connection con = getconnnection();
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    ps.setObject((i + 1), args[i]);
                }
            }
            result = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(ps, con);
        }

        return result;
    }

    /**
     * query, because need to manually close the resource, so not recommended
     * for use it
     * 
     * @param sql
     * @param args
     * @return ResultSet
     */
    @Deprecated  //注解
    public static ResultSet query(String sql, Object... args) {
        ResultSet result = null;
        Connection con = getconnnection();
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    ps.setObject((i + 1), args[i]);
                }
            }
            result = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Query a single record
     * 查询单个记录
     * @param sql
     * @param args
     * @return Map<String,Object>
     */
    public static Map<String, Object> queryForMap(String sql, Object... args) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map<String, Object>> list = queryForList(sql, args);
        if (list.size() > 0) {
            result = list.get(0);
        }
        return result;
    }

    /**
     * Query a single record
     * 查询单个记录返回强类型对象
     * @param sql
     * @param args
     * @return <T>  //泛型
     */
    public static <T> T queryForObject(String sql, Class<T> clz, Object... args) {
        T result = null;
        List<T> list = queryForList(sql, clz, args);
        if (list.size() > 0) {
            result = list.get(0);
        }
        return result;
    }

    /**
     * Query a single record
     * 
     * @param sql
     * @param args
     * @return List<Map<String,Object>>
     */
    public static List<Map<String, Object>> queryForList(String sql, Object... args) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        Connection con = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            con = getconnnection();
            ps = con.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    ps.setObject((i + 1), args[i]);
                }
            }
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<String, Object>();
                for (int i = 1; i <= columnCount; i++) {
                    map.put(rsmd.getColumnLabel(i), rs.getObject(i));
                }
                result.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(rs, ps, con);
        }
        return result;
    }

    /**
     * Query records
     * 查询多个对象,返回强类型集合
     * @param sql
     * @param args
     * @return List<T>
     */
    public static <T> List<T> queryForList(String sql, Class<T> clz, Object... args) {
        List<T> result = new ArrayList<T>();
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = getconnnection();
            ps = con.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    ps.setObject((i + 1), args[i]);
                }
            }
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                T obj = clz.newInstance();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = rsmd.getColumnName(i);
                    String methodName = "set" + columnName.substring(0, 1).toUpperCase()
                            + columnName.substring(1, columnName.length());
                    Method method[] = clz.getMethods();
                    for (Method meth : method) {
                        if (methodName.equals(meth.getName())) {
                            meth.invoke(obj, rs.getObject(i));
                        }
                    }
                }
                result.add(obj);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } finally {
            close(rs, ps, con);
        }
        return result;
    }
}

NFDVDStore.java

package com.zhangguo.dvd.v2;

public class NFDVDStore {

    public static void main(String[] args) {
        DVDStore ds=new DVDStore();
        ds.menu();
    }

}

5.3、运行结果

 

***************************DVD小店欢迎您***************************
1、显示DVD
2、借出DVD
3、归还DVD
4、添加DVD
5、删除DVD
6、编辑DVD
7、退出系统
***************************DVD小店欢迎您***************************
请选择[1-7]:4
名称:镜子
价格:19.3
借出[0/1]:0
添加成功
***************************DVD小店欢迎您***************************
1、显示DVD
2、借出DVD
3、归还DVD
4、添加DVD
5、删除DVD
6、编辑DVD
7、退出系统
***************************DVD小店欢迎您***************************
请选择[1-7]:1
编号:2 名称:异形 价格:75.3 借出:否
编号:3 名称:暗战 价格:19.5 借出:是
编号:4 名称:战狼 价格:9.98 借出:否
编号:8 名称:镜子 价格:19.3 借出:否
***************************DVD小店欢迎您***************************
1、显示DVD
2、借出DVD
3、归还DVD
4、添加DVD
5、删除DVD
6、编辑DVD
7、退出系统
***************************DVD小店欢迎您***************************
请选择[1-7]:2
编号:2 名称:异形 价格:75.3 借出:否
编号:4 名称:战狼 价格:9.98 借出:否
编号:8 名称:镜子 价格:19.3 借出:否
请输入要操作的编号:8
操作成功
***************************DVD小店欢迎您***************************
1、显示DVD
2、借出DVD
3、归还DVD
4、添加DVD
5、删除DVD
6、编辑DVD
7、退出系统
***************************DVD小店欢迎您***************************
请选择[1-7]:3
编号:3 名称:暗战 价格:19.5 借出:是
编号:8 名称:镜子 价格:19.3 借出:是
请输入要操作的编号:8
操作成功
***************************DVD小店欢迎您***************************
1、显示DVD
2、借出DVD
3、归还DVD
4、添加DVD
5、删除DVD
6、编辑DVD
7、退出系统
***************************DVD小店欢迎您***************************
请选择[1-7]:1
编号:2 名称:异形 价格:75.3 借出:否
编号:3 名称:暗战 价格:19.5 借出:是
编号:4 名称:战狼 价格:9.98 借出:否
编号:8 名称:镜子 价格:19.3 借出:否
***************************DVD小店欢迎您***************************
1、显示DVD
2、借出DVD
3、归还DVD
4、添加DVD
5、删除DVD
6、编辑DVD
7、退出系统
***************************DVD小店欢迎您***************************
请选择[1-7]:8
输入有误,请重输
***************************DVD小店欢迎您***************************
1、显示DVD
2、借出DVD
3、归还DVD
4、添加DVD
5、删除DVD
6、编辑DVD
7、退出系统
***************************DVD小店欢迎您***************************

六、下载与视频

第一次课示例:

 https://files.cnblogs.com/files/best/Chapter11.zip

第三次课示例:

https://files.cnblogs.com/files/best/GoMall.zip

139班上课示例1

https://files.cnblogs.com/files/best/Chapter11_136_V2.zip

不断更新的视频:

http://search.bilibili.com/all?keyword=%E5%BC%A0%E6%9E%9C&from_source=banner_search

七、面试题

7.1、请使用JDBC完成产品表Product(编号id,title名称,price价格,address产地)的访问。从控制台完成添加产品,修改产品,删除产品,显示产品功能。可以增加产品状态(State)

7.2、请完成DVD租赁系统

参考示例(139)

八、原生JDBC示例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JdbcTest {

    // 1、添加jar驱动包
    // 2、加载驱动类
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //insert();
        select();
    }

    // 添加
    public static int insert() {
        int n = 0;
        try {
            // 3、获得连接对象
            Connection conn = DriverManager
                    .getConnection(
                            "jdbc:mysql://localhost:3306/dvdshop?useUnicode=true&characterEncoding=UTF-8",
                            "root", "uchr@123");
            // 4、创建SQL命令对象
            PreparedStatement cmd = conn
                    .prepareStatement("insert into dvd(name,price,state) values(?,?,?);");  //ORM
            cmd.setObject(1, "征服");
            cmd.setObject(2, 98.1);
            cmd.setObject(3, 0);
            // 5、执行sql,返回影响行数
            n = cmd.executeUpdate();
            // 6、释放资源
            cmd.close();
            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return n;
    }

    public static void select() {
        try {
            // 3、获得连接对象
            Connection conn = DriverManager
                    .getConnection(
                            "jdbc:mysql://localhost:3306/uchr?useUnicode=true&characterEncoding=UTF-8",
                            "root", "uchr@123");
            // 4、创建SQL命令对象
            PreparedStatement cmd = conn
                    .prepareStatement("select * from list_values");
            // 5、执行sql查询
            ResultSet result = cmd.executeQuery();

            // 6、取得结果集中的数据
            while (result.next()) {
                System.out.print(result.getString(1) + "\t");
                System.out.print(result.getString(2));
                System.out.println();
            }

            // 7、释放资源
            result.close();
            cmd.close();
            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

posted @ 2017-06-01 11:17  张果  阅读(5763)  评论(1编辑  收藏  举报
AmazingCounters.com