【MySQL】JDBC的连接

目录

[一. 具体操作如下](#一. 具体操作如下)

1.注册驱动

二.实操


JDBC(Java DataBase Connectivity)java 数据库连接,是 JavaEE 平台下的技术规范,其定义了在 Java 语言中连接数据,执行 SQL 语句的标准,可以为多种关系数据库提供统一访问。

一. 具体操作如下
1.注册驱动
复制代码
Class.forName("com.mysql.cj.jdbc.Driver");

2.获取连接

DriverManager(驱动管理类)功能如下: 1. 注册驱动 2. 获取数据库连接

法1: 注册与给定的驱动程序 DriverManager 。 public static void registerDriver(Driver driver) throws SQLException

式2:根据url、数据库登录的户名、密码获取个数据库的连接对象。

public static Connection getConnection(String url, String user, Stri ng password)

参数说明:

1.url : 连接路径

语法:jdbc:mysql://ip地址(域名):端号/数据库名称参数键值对1&参数键值对2...

示例:jdbc:mysql://127.0.0.1:3306/db1

1).如果连接的是本机mysql服务器,并且mysql服务默认端是3306,则url可以简写为:jdbc:mysql:///数据库名称参数键值对

(2)JDBC配置 useSSL=false 使户账号密码进连接,useSSL=true:般通过证书或者令牌进安全验证。

(3)JDBC配置useTimezone=true和serverTimezone=GMT%2B8的的是为了解决时区 设置问题,确保Java应程序与MySQL数据库之间的时间同步。

2.user :户名

3.password :密码

4.Connection 数据库连接对象

功能: 1. 获取执 SQL 的对象 2. 管理

复制代码
 String url = "jdbc:mysql://127.0.0.1:3306/数据库名? charset=utf8mb4&useSSL=false&useTimezone=true&serverTimezone=GMT%2B8";
 String user = "数据库账户";
 String password = "数据库密码";
 Connection conn = DriverManager.getConnection(url, user, password);

3.定义sql

复制代码
 String sql = "sql语句";

4.获取sql对象

Connetction类中重要的成员法包括:

  1. 普通执SQL对象: Statement createStatement()法

  2. 创建PreparedStatement类的实例: PreparedStatement prepareStatement(sql)法 预编译SQL的执SQL对象, 通过这种式获取的 PreparedStatement SQL语句执对象是我们 会重点要进讲解的,它可以防SQL注。

    Statement sta = conn.createStatement();

二.实操

1.DriverManager

复制代码
import java.sql.*;
import java.text.MessageFormat;

public class DEMO1_DriverManager {


    public static void main(String[] args) {
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        try {
            //1.加载数据库厂商提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");//指定路径

            //2.获取数据库的连接                 固定写法        IP+端口号       数据库               字符集编码
            connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java114?characterEncoding=utf8&allowPublicKeyRetrieval=true&useSSL=false",
                    "root","hhj048482");//通过实现类来以获取数据库连接Connnection是Java中的类
            //3.创建Statement对象
            statement = connection.createStatement();

            //4.定义SQL语句
            String sql="select id,name,sno,age,gender,enroll_date,class_id from student";

            //5.执行SQL语句
            resultSet = statement.executeQuery(sql);//执行查询
            //statement.executeUpdate();//执行更新执行

            //6.遍历结果集,获取数据行
            while (resultSet.next()) {
                //获取ID列的值
                long aLong = resultSet.getLong(1);
                //resultSet.getLong("id");
                String string = resultSet.getString(2);
                String string1 = resultSet.getString(3);
                int anInt = resultSet.getInt(4);
                Date date = resultSet.getDate(5);
                long aLong1 = resultSet.getLong(7);
                System.out.println(MessageFormat.format("学生编号={0},姓名={1},学号{2},年龄{3},性别={4},入学时间={5},班级编号={6}"
                        ,aLong,string,string1,anInt,date,aLong1));



            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally{
            //释放结果集对象
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }


}

2.DataSource

复制代码
import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class DBUtiL {
    //数据源
    private static DataSource dataSource=null;
    //数据库连接串
    private static final String URL="jdbc:mysql://127.0.0.1:3306/java114?characterEncoding=utf8&allowPublicKeyRetrieval=true&useSSL=false";
    //用户名
    private static final String USER="root";
    //密码
    private static final String PASSWORD="hhj048482";

    //当类加载到JVM的时候,执行数据源的初始化
    static {
        MysqlDataSource mysqlDataSource=new MysqlDataSource();
        mysqlDataSource.setURL(URL);
        mysqlDataSource.setUser(USER);
        mysqlDataSource.setPassword(PASSWORD);
        dataSource = mysqlDataSource;
    }

    //构造方法私有化,防止new这个对象
    private DBUtiL(){}

    /**
     * 获取数据库的连接
     */

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public static void close (ResultSet resultSet, Statement statement, Connection connection) {
        // 释放结果集对象
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        // 释放Statement
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // 关闭数据库连接
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
相关推荐
赵渝强老师15 分钟前
【赵渝强老师】使用Oracle可传输的表空间迁移数据
数据库·oracle
IpdataCloud1 小时前
跨区服玩家延迟高怎么办?用IP离线库自动分配到最近服务器
数据库·tcp/ip·github·php·ip
wuqingshun3141592 小时前
MYSQL默认的事务隔离级别是什么?为什么选择这个级别?
数据库·mysql
空中湖3 小时前
电池简史(五):极限之梦与终章——锂硫、锂空气、量子电池,以及你该知道的电池投资与生活指南
数据库·程序人生
蓝胖子酱4 小时前
在 Electron 中用 electron-store 实现加密存储与自定义格式文件
前端·javascript·数据库
snow@li5 小时前
Redis:数据库语法速查表 / 全景梳理
数据库·redis·缓存
Devlive 开源社区5 小时前
Nebula 1.6.0 发布:跨区域桶自动路由、秒传、文本/PDF 预览一次到位
数据库·sql
这个DBA有点耶5 小时前
导个数据中文全变问号?字符集这事儿真没那么简单
数据库·mysql·代码规范
wuqingshun3141595 小时前
MYSQL中如果发生死锁应该如何解决?
数据库·mysql
DO_Community6 小时前
Weaviate 托管数据库现已在 DigitalOcean 上开放公测
数据库·人工智能·开源·向量数据库·weaviate