JAVA API学习笔记——JDBC

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


什么是JDBC?

JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。

一、使用JDBC的步骤

加载JDBC驱动程序 → 建立数据库连接Connection → 创建执行SQL的语句Statement → 处理执行结果ResultSet → 释放资源

1.加载JDBC驱动程序

//1.加载驱动(开发推荐的方式)
Class.forName("com.mysql.jdbc.Driver");

2.建立数据库连接Connection:

数据库URL:

 URL用于标识数据库的位置,程序员通过URL地址告诉JDBC程序连接哪个数据库,URL的写法为:

在这里插入图片描述

url = jdbc:mysql://localhost:3306/student(库名)?useSSL=false

Connection:

Jdbc程序中的Connection,它用于代表数据库的链接,Collection是数据库编程中最重要的一个对象,客户端与数据库所有交互都是通过connection对象完成的,创建方法为:
Connection conn = DriverManager.getConnection(url, user, password);

3.创建执行SQL的语句Statement :

Jdbc程序中的Statement对象用于向数据库发送SQL语句,创建方法为:

Statement st = conn.createStatement();
在这里插入图片描述
PreperedStatement是Statement的孩子,它的实例对象可以通过调用:
PreperedStatement可以避免SQL注入的问题。
PreperedStatement st = conn.preparedStatement()

 connection = JDBCUtils.getConnection();
//          使用preparedStatement用问号代替输入的数据
            System.out.println("请输入要插入的姓名和年龄(用回车隔开):");
            Scanner scanner = new Scanner(System.in);
            String name = scanner.nextLine();
            int age = scanner.nextInt();
            String sql ="INSERT into student(name,age) values (?,?)";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,name);
            preparedStatement.setInt(2,age);

            int result = preparedStatement.executeUpdate();
            if(result >0){
                System.out.println("insert success");
            }

4. 处理执行结果ResultSet:

执行查询
Statement接口的executeQuery()方法用于执行对数据库的查询。此方法返回ResultSet的对象,该对象可用于获取表的所有记录。

public ResultSet executeQuery(String sql)throws SQLException

5.释放资源:

Jdbc程序运行完后,切记要释放程序在运行过程中,创建的那些与数据库进行交互的对象,这些对象通常是ResultSet, Statement和Connection对象。

package com.google.JDBC;

import java.sql.*;

public class JDBCTest {
    public static final String URL = "jdbc:mysql://localhost:3306/student&useSSL=true";
    public static final String USER = "root";
    public static final String PASSWORD= "123456";

    public static Connection connection;
    public static Statement statement;
    public static ResultSet result;

    public static void main(String[] args) {
        try {
//      1.加载驱动程序
            Class.forName("com.mysql.jdbc.Driver");
//      2.获取数据库链接对象
            connection =  DriverManager.getConnection(URL,USER,PASSWORD);
//      3.获取数据库的操作对象
            statement = connection.createStatement();
            result = statement.executeQuery("select *from student");
            while(result.next()){
                int id = result.getInt(1);
                String name  = result.getString(2);
                int age = result.getInt(3);
                System.out.println("id:"+id + " name:"+name+" age:"+age);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                result.close();
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }
}

二、封装JDBCUtill

package com.google.JDBC;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    private static String driver;
    private static String url;
    private static String user;
    private static String password;

//  通过静态代码块,来预先执行读取配置文件的配置项,做预处理
    static {
        try {
            InputStream inputStream = ClassLoader.getSystemResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(inputStream);

            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");

//            System.out.println(driver+", "+url+", "+user+", "+password);

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

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }
    public static void close(Connection connection, PreparedStatement preparedStatement) throws SQLException {
        if(preparedStatement!=null){
            preparedStatement.close();
        }
        if(connection!=null){
            connection.close();
        }
    }
    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) throws SQLException {
        if(resultSet!=null){
            resultSet.close();
        }
        if(preparedStatement!=null){
            preparedStatement.close();
        }
        if(connection!=null){
            connection.close();
        }

    }
    public static void close(Connection connection, Statement statement) throws SQLException {
        if(statement!=null){
            statement.close();
        }
        if(connection!=null){
            connection.close();
        }
    }
    public static void close(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
        if(resultSet!=null){
            resultSet.close();
        }
        if(statement!=null){
            statement.close();
        }
        if(connection!=null){
            connection.close();
        }

    }

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值