我是靠谱客的博主 机灵凉面,这篇文章主要介绍springboot项目中使用原生jdbc连接MySQL数据库,现在分享给大家,希望可以做个参考。

第一步:pom.xml中添加依赖;

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
第二步:编写连接类

package com.example.demo.controller;
import java.lang.*;
import java.sql.*;
 
public class JDBCDemo {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
//      Class.forName("com.mysql.jdbc.Driver");
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://127.0.0.1:3306/mysql?serverTimezone=GMT%2B8";
//      String url = "jdbc:mysql://127.0.0.1:3306/mysql";
        Connection con = DriverManager.getConnection(url, "root", "123");
        Statement statement = con.createStatement();
        ResultSet resultSet = statement.executeQuery("select * from db");
        while(resultSet.next()){
            System.out.println(resultSet.getString(1));
        }
    }
}
执行结果:

注:问题记录

1.数据库密码错误会报错“Exception in thread "main" java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)”

2.url中未加参数‘serverTimezone=GMT%2B8’,会报下面的错误;

3.mysql驱动,使用

"com.mysql.jdbc.Driver"
会报如下警告:

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

换成

"com.mysql.cj.jdbc.Driver"
即可


 
————————————————
版权声明:本文为CSDN博主「一粒小石子」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq516071744/article/details/86499027

最后

以上就是机灵凉面最近收集整理的关于springboot项目中使用原生jdbc连接MySQL数据库的全部内容,更多相关springboot项目中使用原生jdbc连接MySQL数据库内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部