JDBC操作数据库

JDBC操作数据库的步骤

  1. 注册驱动(通过Class.forName())
     Class.forName("com.mysql.jdbc.Driver");
  1. 获得连接(通过DriverManager.getConnection())
            String url = "jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8";
            String user=  "用户";
            String password= "密码";
            Connection connection = DriverManager.getConnection(url,user,password);
            
    url(地址):jdbc:mysql://ip或主机:端口号/数据库名
  1. 写SQL语句
        String sql = " ";
  1. 获得statement容器
        Statement statement = connection.createStatement();
  1. 执行SQL语句,获得结果集(resultSet )
        ResultSet resultSet = statement.executeQuery(sql);
  1. 处理结果集
            while(resultSet.next()){
                int id = resultSet.getInt(1);
                String name = resultSet.getString("class_name");
                int num = resultSet.getInt("class_num");
                System.out.println(id+"-"+name+"-"+num);
            }
  1. 关闭资源
finally {
            try {
                try{
                    if(resultSet != null){
                        resultSet.close();
                    }
                }finally {
                    try{
                        if(statement != null){
                            statement.close();
                        }
                    }finally {
                        try{
                            if(connection != null){
                                connection.close();
                            }
                        }finally {

                        }
                    }
                }

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

注意:倒着释放资源
原因:防止空指针
     finally继续关闭其他资源
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值