栋哥带你学Java之JDBC

JDBC
什么是JDBC?
JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句
的JavaAPI,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成.JDBC提供了一种基准,可以构建更高级的工具和接口,使数据库开发人员能够编写数
据库应用程序.
JDBC的四个核心类:
DriverManager:创建连接
Connection:连接类
Statement:执行SQL语句
RestultSet:执行SQL语句后的结果集
JDBC连接数据库的步骤?
1.先注册驱动
2.获取连接
3.获取SQL语句的执行对象
4.执行SQL语句,并接收返回集
5.对返回集进行处理
6.关闭资源

栋哥带你学Java之JDBC_第1张图片

准备工作:先创建一个myjdbc的数据库,并且创建一张users表,并添加几条数据.
public class Demo01 {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        // 注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 获取连接
        // url是 访问数据库的链接地址
        String url = "jdbc:mysql://localhost:3306/myjdbc";
        // 获取连接方式一
        Connection connection = DriverManager.getConnection(url, "root", "123456");
        // 获取连接的方式二
//      Properties info = new Properties();
//      // 添加用户名 密码
//      info.setProperty("user", "root");
//      info.setProperty("password", "123456");
//      Connection connection = DriverManager.getConnection(url, info);
        // 获取连接方式三
        // 携带参数 访问连接
        String url2 = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
        Connection connection = DriverManager.getConnection(url2);
        // 获取执行SQL语句的对象 Statement
        Statement statement = connection.createStatement();
        // 执行SQL语句 返回结果集
        // 结果集中添加 的索引 要和 查询语句中的字段对应
        String sql = "select * from users";
        ResultSet resultSet = statement.executeQuery(sql);
        // 处理结果集
        // 循环遍历结果集 输出结果
        // 有记录 next()方法 返回true 反之
        while (resultSet.next()) {
            // 打印数据
            // 注意:查询数据库时 索引从1开始
            System.out.println(resultSet.getObject(1));
            System.out.println(resultSet.getObject(2));
            System.out.println(resultSet.getObject(3));
            System.out.println(resultSet.getObject(4));
            System.out.println(resultSet.getObject(5));

        }
        // 关闭资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}
解析:注册驱动的话,要写全限定类名,不然系统就不知道是找什么包下的Driver类.url
是访问数据库的连接地址,mysql是你自己使用的数据库,3306是数据库的端口号,如果你
自己修改过端口号的就填写你自己改过后的,myjdbc就是要查询的数据库名.获取连接总
共有三种方式,一般是推荐使用第一种,第二种的话要使用集合,第三种的写法不适合密码
符号比较多的,比如密码里有等号之类的,这样使用第三者写法就比较麻烦.resultSet就
是根据SQL语句查询出来的结果集,resultSet.next()是判断是否还有记录,这涉及到
指针,不调用next方法前指针是指向字段那一行的.resultSet.getObject(1),里面
的数字是字段的顺序,按照数据表中1就是id那个字段.使用完后记得关闭资源.
增删改查代码示例:
public class DemoCRUD {
    // 注解 用来测试方法
    // 注意:要使用public修饰 无返回值方法
    @Test
    public void testInsert() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
        Connection connection = DriverManager.getConnection(url);
        Statement statement = connection.createStatement();
        String sql = "insert into users values(5,'哈哈','000','[email protected]','2004-05-05')";
        // row受影响的行数
        int row = statement.executeUpdate(sql);
        System.out.println(row);
        statement.close();
        connection.close();
    }

    @Test
    public void testUpdate() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
        Connection connection = DriverManager.getConnection(url);
        Statement statement = connection.createStatement();
        String sql = "update users set name = 'xixi' where id = 5";
        int executeUpdate = statement.executeUpdate(sql);
        System.out.println(executeUpdate);
        statement.close();
        connection.close();
    }

    @Test
    public void testDelete() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
        Connection connection = DriverManager.getConnection(url);
        Statement statement = connection.createStatement();
        String sql = "delete from users where id = 5";
        int executeUpdate = statement.executeUpdate(sql);
        System.out.println(executeUpdate);
        statement.close();
        connection.close();
    }

    @Test
    public void testSelect() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
        Connection connection = DriverManager.getConnection(url);
        Statement statement = connection.createStatement();
        // 查询
        String sql = "select id,name,email from users";
        ResultSet resultSet = statement.executeQuery(sql);
        // 处理结果集
        while (resultSet.next()) {
            System.out.println(resultSet.getObject("id"));
            System.out.println(resultSet.getObject("name"));
            System.out.println(resultSet.getObject("email"));
        }

        statement.close();
        connection.close();
    }
}
解析:使用注解@Test就可以直接测试带代码正确不正确,不需要再写main函数了,方便测
试.statement.executeUpdate(sql);这句代码返回值是int类型的,而它的值就是
表示执行完SQL语句后受到影响的行数.resultSet.getObject("id");上面
getObject的参数类型是int类型的表示字段的位置,而这个方法同样也提供传入
String类型的,直接填写字段的名字也是一样的效果的,因为有时候不需要查看全部的字
段.
注意:这种写法不知道大家是否发现有很多重复的代码,而且每执行一个方法就重新注册了
一次驱动,完全没必要,下面提供大家一个更简单的方法.
准备工作:在src下创建一个文件,我起的名字叫dbinfo.properties.
文件里面的内容如下:
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/myjdbc
user=root
password=123456
代码如下:
public class JDBCUtil {
    private static String driverClass;
    private static String url;
    private static String user;
    private static String password;
    // 使用静态代码块加载驱动 读取配置文件
    static {
        // 使用系统类来读取配置文件
        ResourceBundle rb = ResourceBundle.getBundle("dbinfo");
        // 获取文件中的数据
        driverClass = rb.getString("driverClass");
        url = rb.getString("url");
        user = rb.getString("user");
        password = rb.getString("password");
//      Properties properties = new Properties();
//      FileInputStream fis;
//      try {
//          fis = new FileInputStream("src/dbinfo.properties");
//          properties.load(fis);
//          // 读文件
//          driverClass = properties.getProperty("driverClass");
//          url = properties.getProperty("url");
//          user = properties.getProperty("user");
//          password = properties.getProperty("password");
//      } catch (FileNotFoundException e) {
//          e.printStackTrace();
//      } catch (IOException e) {
//          e.printStackTrace();
//      }
//      // 让驱动类只加载一次
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    // 获取数据库连接的方法
    public static Connection getConnection() throws ClassNotFoundException, SQLException {      
        return DriverManager.getConnection(url,user,password);
    }
    // 关闭数据库的方法 如果没有结果集需要关闭 直接传null(空值)就行
    public static void closeAll(ResultSet resultSet,Statement statement,Connection connection) {
        // 关闭资源前要非空判断 防止空指针出现
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException("关闭失败");
            }
            // 加快系统回收的速度
            resultSet = null;
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException("关闭失败");
            }
            // 加快系统回收的速度
            resultSet = null;
        }           
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException("关闭失败");
            }
            // 加快系统回收的速度
            connection = null;
        }   
    }
}
解析:为什么后缀名要用properities.因为Properties集合是所有集合中可以直接操
作流的集合,用这个后缀名表示这是个配置文件.读取文件里的信息除了用该集合外,系统
也提供了一个类ResourceBundle.该类里提供了一个静态的方getBundle();这个方法
里直接写配置文件的名字就行了,后缀名都不用写.把只需要执行一次的带代码都写在代码
块里就行了.

你可能感兴趣的:(Java)