【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();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值