数据库——jdbc编程

数据库——jdbc编程

JDBC编程六步:
在这里插入图片描述

import java.sql.*;
import java.util.ResourceBundle;

public class JDBC_Test {
    public static void main(String[] args) {

        //使用资源绑定器绑定属性配置文件
        ResourceBundle boundle= ResourceBundle.getBundle("jdbc");
        String driver=boundle.getString("driver");
        String url=boundle.getString("url");
        String user=boundle.getString("user");
        String password=boundle.getString("password");

        Connection cnn=null;
        Statement stmt=null;
        ResultSet res=null;

        try {
            //第一步:注册驱动(这种方式是比较常用的)
            //以下方法是不需要接收返回值的,因为我们只是想要它的类加载动作(类加载的时候执行类的静态代码块)
            Class.forName(driver);
            //第二步:获取连接
            //url包括协议、IP、port、资源名
            cnn= DriverManager.getConnection(url,user,password);
            //第三步:获取数据库操作对象
            stmt=cnn.createStatement();
            //第四步:执行SQL语句
            String sql= "select empno,ename,sal from emp";
            //int count =stmt.executeUpdate(sql);执行的sql是DML语句,返回值是“影响数据库中的记录条数”
            res=stmt.executeQuery(sql);//执行的DQL语句,返回的是查询结果集
            //第五步:处理查询结果
            while (res.next()){
                //getString(查询结果集的列名称),
                String empno=res.getString("empno");
                String ename=res.getString("ename");
                String sal=res.getString("sal");
                System.out.println(empno+","+ename+","+sal);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //第六步:释放资源(为了资源一定释放,在finally语句块中关闭资源)
            //遵循从小到大一次关闭
            //分别对其try...catch
            if (res != null) {
                try {
                    res.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt!= null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (cnn != null) {
                try {
                    cnn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

上面用的jdbc.properties文件如下:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值