Java中操作数据库语句JDBC基础

JDBC

    JDBC Java Database connectivity
    Java数据库连接规范(一套接口) 由SUn公司提供的

    JDBC四个核心类
    DriverManager 创建连接
    Connection 连接类
    Statement 执行sql语句
    ResultSet 结果集

    JDBC连接步骤:
    1.注册驱动
    2.获取连接 Connection
    3.获取sql 语句的执行对象 Statement
    4.执行sql 语句 返回结果集
    5.处理结果集
    6.关闭资源

JDBC 连接

    // 注册驱动
        // 这种注册方式 相当于注册了两遍 
        // Driver 类 内部的静态代码块 已经注册了一遍
        //DriverManager.registerDriver(new Driver());
        // 直接把该类加载到内存当中 参数是 全限定类名
        // 包名+类名
        Class.forName("com.mysql.jdbc.Driver");
        // 获取连接对象 
        // url 是访问数据库 链接地址
        // 3306是数据库的端口号
        // myjdbc是库名
        String url = "jdbc:mysql://localhost:3306/myjdbc";
        // 连接方式一
        // root是数据库账号
        // 123456是数据库密码
        // Connection connection = DriverManager.getConnection(url, "root", "123456");

        /*
        //获取连接的方式2
        Properties info = new Properties();
        // 添加用户名 密码
        // 注意键值别拼错了
        info.setProperty("user", "root");
        info.setProperty("password", "123456");
        Connection connection = DriverManager.getConnection(url, info);
        */

        // 获取连接方式3 相当于使用了一个get请求
        // 携带参数 访问链接
        String url2 = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
        Connection connection = DriverManager.getConnection(url2);

        // 获取执行sql语句的对象 Statement
        Statement statement = connection.createStatement();
        // 执行sql语句 返回结果集

        // users 是表名
        String sql = "select * from users";
        ResultSet resultSet = statement.executeQuery(sql);
        // 处理结果集
        // 循环遍历结果集 输出结果
        // 有记录 next()方法 返回true 反之 返回 false
        // next方法是查看数据库下一条记录有没有值
        // 有就返回true 没有就返回false
        while (resultSet.next()) {
            // 打印数据
            // 结果集中添加的 索引 要和 查询语句中的 字段对应
            // 注意:查询数据库时 索引从1开始
            // 这里的12345 是数据库列的索引
            // 1 代码 id
            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));
            System.out.println("--------------------");
        }
        // 关闭资源
        resultSet.close();
        statement.close();
        connection.close();
    }

测试增删改查

        // 注解 用来测试方法
    // 注意: 要使用public修饰 无返回值方法

    // 插入方法
    @Test
    public void testInsert() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/myjdbc";
        Connection connection = DriverManager.getConnection(url, "root", "123456");

        Statement statement = connection.createStatement();
        String sql = "insert into users values(5,'f','123456','w@qq.com','1997-06-01')";
        int row = statement.executeUpdate(sql);
        if (row > 0) {
            System.out.println("插入成功");
        }

        statement.close();
        connection.close();

    }
    // 修改方法
    @Test
    public void testUpdate() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/myjdbc";
        Connection connection = DriverManager.getConnection(url, "root", "123456");

        Statement statement = connection.createStatement();
        String sql = "update users set name = 'g' where name='f'";
        // 受影响的行数
        int update = statement.executeUpdate(sql);
        if (update > 0) {
            System.out.println("更新成功" + update + "行");
        }

        statement.close();
        connection.close();

    }

    // 删除方法
    @Test
    public void testDelete() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/myjdbc";
        Connection connection = DriverManager.getConnection(url, "root", "123456");

        Statement statement = connection.createStatement();
        String sql = "delete from users where id=5 ";
        int row = statement.executeUpdate(sql);
        if (row > 0) {
            System.out.println("删除成功");
        }

        statement.close();
        connection.close();

    }

    // 查询方法
    //@Test写入时需要选择导入 import org.junit.Test;
    @Test
    public void testSelect() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/myjdbc";
        Connection connection = DriverManager.getConnection(url, "root", "123456"); 
        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"));
        }
        resultSet.close();
        statement.close();
        connection.close();

    }

连接数据库的异常处理

    Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/myjdbc";
            connection = DriverManager.getConnection(url, "root", "123456");
            statement = connection.createStatement();
            String sql = "select * from users";
            resultSet = statement.executeQuery(sql);
            // 处理结果集(把数据库的记录封装到对象中)
            // 把对象保存到数组当中并遍历打印
            // 创建集合
            ArrayList<User> arrayList = new ArrayList<>();
            while (resultSet.next()) {
                // 创建User对象
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setPassword(resultSet.getString("password"));
                user.setEMail(resultSet.getString("email"));
                user.setBirthday(resultSet.getDate("birthday"));
                // 放入集合当中
                arrayList.add(user);
            }
            // 遍历查看
            for (User user : arrayList) {
                System.out.println(user);
            }
        } catch (ClassNotFoundException e) {
            // 停止程序
            throw new RuntimeException("驱动加载失败");
        } catch (SQLException e) {
            throw new RuntimeException("获取连接失败");
        } finally {
            // 关闭资源前 要做非空判断 防止空指针出现
            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("关闭失败");
                }
                // 加快系统回收的速度
                statement = null;
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException("关闭失败");
                }
                // 加快系统回收的速度
                connection = null;
            }
        }

JDBC工具类


    //在src目录下创建一个文件
    //文件名为 dbinfo.properties
    //将以下代码写入文件中
    //这个文件成为配置文件
    driverClass=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/myjdbc
    user=root
    password=123456

    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();
//      try {
//          FileInputStream 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 (IOException e) {
//
//      }

        // 让驱动类只加载一次
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 获取数据库的连接方法
    public static Connection getConnection() throws SQLException, ClassNotFoundException {
        return DriverManager.getConnection(url, user, password);
    }

    // 关闭数据库的方法 如果没有结果集需要关闭 直接传空就好了
    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("关闭失败");
            }
            // 加快系统回收的速度
            statement = null;
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException("关闭失败");
            }
            // 加快系统回收的速度
            connection = null;
        }
    }


    // 创建测试类 测试 JDBC工具类

    @Test
    public void testSelect() {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        // 获取连接
        try {
            connection = JDBCUtil.getConnection();
            statement = connection.createStatement();
            String sql = "select * from users";
            resultSet = statement.executeQuery(sql);
            // 创建集合
            ArrayList<User> arrayList = new ArrayList<>();
            while (resultSet.next()) {
                // 创建User对象
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setPassword(resultSet.getString("password"));
                user.setEMail(resultSet.getString("email"));
                user.setBirthday(resultSet.getDate("birthday"));
                // 放入集合当中
                arrayList.add(user);
            }
            // 遍历查看
            for (User user : arrayList) {
                System.out.println(user);
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            // 关闭资源
            JDBCUtil.closeALL(resultSet, statement, connection);
        }
    }
  • 8
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值