JAVA-JDBC(初级入门)

来源:互联网 发布:kitti 数据集怎么使用 编辑:程序博客网 时间:2024/06/05 16:57

首先我们得了解JDBC到底是什么

²  用官方的话来说

l  JDBC全称为:Java DataBase Connectivity(java数据库连接)。

l  SUN公司为了简化、统一对数据库的操作,定义了一套Java操作数据库的规范,称之为JDBC。

²  用图来解释呢就是这样的

JDBC怎么用呢?

²  JDBC的使用分为六个步骤

1.       注册驱动

2.       获得连接

3.       获得Statement对象

4.       执行sql语句获得结果集对象

5.       解析结果集(查询语句需要用到此步骤)

6.       释放资源

²  下面代码演示

@Testpublic void test() {Connection connection = null;Statement createStatement = null;ResultSet executeQuery = null;try {// 1、注册驱动因为驱动文件中已经静态初始化了加载了驱动,所以我们只需要把这个驱动加载到类加载器即可Class.forName("com.mysql.jdbc.Driver");// 2、获得连接地址值数据库账户名与登录密码connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1", "root", "123");// 3、获得statement对象createStatement = connection.createStatement();// 4、执行sql语句获得结果集对象sql语句executeQuery = createStatement.executeQuery("select * from user");// 5、解析结果集由于初始“指针”在第一行上方,所以要先指针下移才是第一行数据while (executeQuery.next()) {System.out.println(executeQuery.getString("id"));//获取当前行列名为ID的值System.out.println(executeQuery.getString("userName"));//获取当前行列名为userName的值System.out.println(executeQuery.getString("passUser"));//获取当前行列名为passUser的值}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} finally {// 6、释放资源try {executeQuery.close();//释放资源} catch (SQLException e) {e.printStackTrace();}executeQuery = null;//斩断对象栈堆引用指向,迫使GC进行垃圾回收try {createStatement.close();//释放资源} catch (SQLException e) {e.printStackTrace();}createStatement = null;//斩断对象栈堆引用指向,迫使GC进行垃圾回收try {connection.close();//释放资源} catch (SQLException e) {e.printStackTrace();}connection = null;//斩断对象栈堆引用指向,迫使GC进行垃圾回收}}

原创粉丝点击