Java学习笔记Day6.10——JDBC

JDBC
一  基本概念;JDBC(Java DataBase Connectivity)是一组通过用Java语言编写的类和接口组成的APi来实现Java和数据库之间通信与交互的一个桥梁。

二 常用的类与接口

  • Driver 有数据库管理系统实现该接口, 来实现加载对应数据库管理系统的驱动程序.
  • DriverManger 一个具体的类,提供一套比较基础的Driver管理服务。
  • Collenction 一个数据库的连接对象,相当于一个对话.
  • Statement 执行SQL语句的载体.一般我们不用该接口直接去执行SQL语句,而是使用它的子类
  • PreparedStatement Statement的子类,使用占位符?来填充具体的SQL语句,  安全性比Statement高 .
  • RestultSet SQL 结果集对象语句执行的返回结果,一般是Select语句

三  使用步骤

  1.  注册并加载MySQL驱动Driver(提前导入mysql的 jar 包)
  2.  建立并获取数据库连接对象(建立JDBC和数据库之间的Connection连接)
  3.  准备SQL语句,
  4.  获取SQL语句发送器,来执行SQL语句
  5.  发送并执行SQL语句,得到结果集
  6.  处理结果集返回到ResultSet中
  7.  结束并释放资源

四 具体实现
     4.1 加载数据库驱动
 

Class.forName("com.mysql.jdbc.Driver"); 

注;Class.forName需要捕获ClassNotFoundException.
Class.forName是把这个类加载到JVM中,加载的时候,就会执行其中的静态初始化块,完成驱动的初始化的相关工作。

   4.2 获取数据库连接对象

Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student?characterEncoding=utf-8","root","123456"); 

这里需要提供:数据库服务端的IP地址:127.0.0.1 
如果连接其他电脑上的数据库,需填写相应的IP地址
本地服务器,直接使用localhost作为数据库名称

                         数据库的端口号: 3306 (mysql专用端口号)
                         数据库名称 student(根据你自己数据库中的名称填写)
                         编码方式 UTF-8
                         账号 root
                         密码 123456(如果你在创建数据库的时候没有使用默认的账号和密码,请填写自己设置的账号和密码)

Connection是与特定数据库连接回话的接口,使用的时候需要导包,而且必须在程序结束的时候将其关闭。getConnection方法也需要捕获SQLException异常。

因为在进行数据库的增删改查的时候都需要与数据库建立连接,所以可以在项目中将建立连接写成一个静态的工具方法,用的时候直接调用即可:

 /**
     * 取得数据库的连接
     * @return 一个数据库的连接
     */
public static Connection getConnection(){
        Connection conn = null;
         try {//初始化驱动类com.mysql.jdbc.Driver
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/student?characterEncoding=UTF-8","root", "123456");
                //该类就在 mysql-connector-java-5.0.8-bin.jar中,如果忘记了第一个步骤的导包,就会抛出ClassNotFoundException
            } catch (ClassNotFoundException e) {                 
                e.printStackTrace();
            }catch (SQLException e) {                            
                e.printStackTrace();
            }
         return conn;

    
 4.3 创建Statement或者PreparedStatement接口,准备执行SQL语句

  • Statement接口
String sql = "INSERT INTO grade(id,name,clsses,credit)VALUES(?,?,?,?)";
Statement ss = connection.Statement(sql);


其中 ,增删改只需要改变SQL语句的内容就能完成,然而查询略显复杂。
在Statement中使用字符串拼接的方式,该方式存在句法复杂,容易犯错等缺点,
所以Statement在实际过程中使用的非常的少,大多数使用的还是PreparedStatement,

  • PreparedStatement接口
String sql = "INSERT INTO grade(id,name,clsses,credit)VALUES(?,?,?,?)";
PreparedStatement ps = connection.prepareStatement(sql);


PreparedStatement是Statement的实现类.比Statement更加的安全.用于执行的SQL语句预编译语句. 同时数据库管理系统也该语句进行了缓存,使得重复执行速度更快.

  • execute() 普通的运行语句,返回为boolean类型,是否有结果集
  • executeQuery() 带有ResultSet的查询,一般是select语句
  • addBatch() 批处理,执行大量相同的语句是,可以使用批处理
  • clearBatch() 清空Batch
  • executeBatch() Batch积累一定量,执行Batch.
  • executeUpdate() 运行增删改操作,返回更新的行数

使用PreparedStatement需要根据sql语句创建PreparedStatement。除此之外,还能够通过设置参数,指定相应的值,而不是Statement那样使用字符串拼接。
在使用完的时候,也需要进行关闭。
4.4 来执行SQL语句
对数据库中的表进行增删改查等操作语句

String sql = "INSERT INTO grade(id,name,clsses,credit)VALUES(?,?,?,?)";
String sql = "INSERT INTO grade(id,name,clsses,credit)VALUES(?,?,?,?)";


4.5  发送并执行SQL语句,处理得到结果集
 ResultSet rs = statement.executeQuery(sql);


4.6 结束并释放资源
rs.close();
statement.close();
PreparedStatement.close();


RestultSet SQL  返回结果集
封装查询结果
常用方法:

  • boolean next(): 游标向下移动一行
  • int getInt(int columnIndex): 获取一个 int 类型的值 (传编号[编号从1开始] 或 列名)
  • int getInt(String columnLabel)
  • String getString(int columnIndex): 获取一个 String 类型的值 (传编号 或 列名)
  • String getString(String columnLabel)
  •  

一个完整的例子;

package com.qf.jdbc.Dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.qf.jdbc.entity.User;
import org.junit.Test;


public class UserDao {

    //设置连接数据库的配置项
    private Connection connection = null;//数据库连接对象
    private Statement statement = null;// 执行SQL语句
    private ResultSet rs=null;//返回的结果集对象
    
    @Test
    public void test01(){
        try {
            // 1 加载数据库驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 2 获取数据库连接
            connection = DriverManager.getConnection("jdbc:mysql:///student?characterEncoding=utf-8", "root", "123456");
            // 3 创建statement
            Statement statement = connection.createStatement();
            
            //设置取消自动提交,使之能够进行回滚——如果不设置,执行完毕SQL语句,会都自动的关闭,将会报无法执行回滚操作的错
            connection.setAutoCommit(false);
            
            // 4 准备sql语句,对数据库中的表进行操作
            String sql="SELECT * FROM grade";
            
            // 5 执行SQL语句
            rs = statement.executeQuery(sql);
            
            List users = new ArrayList<>();
            // 读取数据库目标表grade的信息
            while(rs.next()) {
                
                int userId1 = rs.getInt("id");
                String userName = rs.getString("name");
                String userclass = rs.getString("clsses");
                int usercredit = rs.getInt("credit");
                
                User user = new User(userId1, userName, userclass,usercredit);
                users.add(user);
            }
            //手动提交
            connection.commit();
            System.out.println(users);
            
        // 开启的对象或流需要逐一关闭
        } catch (Exception e) {
            //事务回滚
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
            //关闭
            if(rs!=null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(statement!=null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }    
    }
    
}

 

你可能感兴趣的:(Java学习日记)