初学JDBC

public class Test01 {
    public static void main(String[] args) {
        //1.准备工作
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        //2.从配置文件中获取驱动,url路径,用户名和密码;getBundle("db")文件名不要带后缀名
        //ResourceBundle对象专门用于获取配置文件,采用键值对方式存储数据
        ResourceBundle resourceBundle = ResourceBundle.getBundle("db");
        String className = resourceBundle.getString("className");
        String url = resourceBundle.getString("url");
        String name = resourceBundle.getString("name");
        String password = resourceBundle.getString("password");

        try {
            //3.注册驱动
            Class.forName(className);
            //4.获取数据库链接对象
            conn = DriverManager.getConnection(url, name, password);
            //5.编写sql语句
            String sql = "select * from student";
            //6.获取sql语句操作对象
            stmt = conn.prepareStatement(sql);
            //7.执行sql语句
            rs = stmt.executeQuery();
            //8.处理结果集
            //获取数据库字段个数
            int columnCount = rs.getMetaData().getColumnCount();
            //rs.next() 类似于迭代器,一个是可以判断结果集还有没有数据,
            //一个是可以移动指针
            while (rs.next()) {
                //打印一行数据
                for (int i = 1; i <= columnCount; i++) {
                    System.out.print(rs.getObject(i) + "\t");
                }
                //换行
                System.out.println();
            }

        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
        //9.关闭资源,关闭资源顺序和使用资源的顺序相反,
        //因为后面的资源使用是在前面的资源的基础上进行的,所以先关后面的。
        finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

db.properties

className=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/school
name=root
password=root

注:如果是MySQL8以后的版本要用  com.mysql.cj.jdbc.Driver,

MySQL5的用com.mysql.jdbc.Driver

配置文件存放目录应为src的根目录

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值