这篇文章给大家介绍使用Java怎么连接MySQL8.0 JDBC,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
一.导入jar包



2.导入
在项目文件夹下新建一个名为lib的文件夹

将下载好的jar包放入lib文件夹,然后右击lib文件夹,选择Add as Library...,然后点击ok


二.代码部分
1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
2.用户信息和url
String url = "jdbc:mysql://localhost:3306/数据库名?&useSSL=false&serverTimezone=UTC";
3.数据库对象Connection
Connection connection = DriverManager.getConnection(url,username,password);
4.执行数据库对象connection
Statement statement = connection.createStatement();
代码展示
package com.lofun.fuxi.JDBC;
import java.sql.*;
public class jdbc_used {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println( "加载驱动成功!" );
//2.用户信息和url
String url = "jdbc:mysql://localhost:3306/练习?&useSSL=false&serverTimezone=UTC";
String username = "root"; //数据库用户名
String password = "123456";//数据库密码
//3.连接成功,数据库对象Connection代表数据库
Connection connection = DriverManager.getConnection(url,username,password);
//4.执行SQL的对象Statement
Statement statement = connection.createStatement();
String sql = "SELECT * FROM students";
ResultSet resultSet_01 = statement.executeQuery(sql);//查询的结果集,封装了所有的查询结果 statement.executeQuery()执行sql语句
while(resultSet_01.next()){
System.out.println(resultSet_01 .getObject("name"));//resultSet_01 .getObject获取指定的数据类型
}
//关闭
resultSet_01.close();
statement.close();
connection.close();
}
}
关于使用Java怎么连接MySQL8.0 JDBC就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。