Java JDBC连接数据库

JDBC的概念

JDBC  Java Database connectivity
Java数据库连接规范(一套接口) Sun公司提供的
是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,
它由一组用Java语言编写的类和接口组成。
JDBC提供了一种基准,据此可以构建更高级的工具和接口,
使数据库开发人员能够编写数据库应用程序
   JDBC四个核心类
   DriverManager 创建连接
   Connection    连接类
   Statement      执行sql语句
   ResultSet      结果集

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

连接数据库基础操作

// 注册驱动
// 这种注册方式相当于注册了两遍 Driver类内部的静态代码块
// DriverManager,registerDriver(new Driver());
// 直接把该类加载到内存当中 参数是权限定类名(包名+类名)
Class.foName("com.mysql.jdbc.Driver");
// 获取连接对象
// url 是访问数据库的连接地址
String url = "jdbc:mysql://localhost:3306/myjdbc";
// 连接方式1
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 = connection.creatStatement();
// 执行sql语句 返回结果集
// 结果集中添加的索引 要和 查询语句中的字段对应
String sql = "select * from users";
ResultSet resultSet = statement.executeQuery(sql);
// 处理结果集
// 循环遍历结果集 打印输出结果
// 有数据 next()方法才会返回true
while(result.next()){
// 打印数据
// 注意查询数据库时 索引从1开始
System.out.println(resultSet.getObject(1));
System.out.println(resultSet.getObject(2));
}
// 关闭资源
resultSet.close();
statement.close();
connection.close();

连接数据的异常处理

public static void main(String[] args) {
        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> list = new ArrayList<>();
            while (resultSet.next()) {
                // 创建 User 对象
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setEmail(resultSet.getString("email"));
                user.setPassword(resultSet.getString("password"));
                user.setBirthday(resultSet.getDate("birthday"));
                list.add(user);     
            }

            // 遍历查看
            for (User user : list) {
                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;
            }   
        }
    }

对数据库的增删改查

// 注解 用来测试方法
    // 注意: 要使用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();
        // executeUpdate 增删改使用
        String sql = "insert into users values (5,'rs', '567','qq@567','1994-09-22')";
        // 受影响的行数
        int row = statement.executeUpdate(sql);
        System.out.println(row);
        if (row > 0) {
            System.out.println("插入成功");
        }
        statement.close();
        connection.close();

    }
    // 更新
    @Test
    public void test1() 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();
        // executeUpdate 增删改使用
        String sql = "update users set name='haha' where id=5";
        // 受影响的行数
        int row = statement.executeUpdate(sql);
        System.out.println(row);
        if (row > 0) {
            System.out.println("更新成功" + row + "行");
        }
        statement.close();
        connection.close();
    }
    // 删除
    @Test
    public void test2() 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();
        // executeUpdate 增删改使用
        String sql = "delete from users where id=5;";
        // 受影响的行数
        int row = statement.executeUpdate(sql);
        System.out.println(row);
        if (row > 0) {
            System.out.println("删除成功");
        }
        statement.close();
        connection.close();
    }
    // 查询方法
    @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();
    }

封装方法连接数据库

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();
        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) {
            // TODO Auto-generated catch block
            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;
        }   
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值