Java连接MySQL8.0 JDBC的详细步骤(IDEA版本)

 更新时间:2021年4月6日 20:00  点击:2608

一.导入jar包

  1.下载jar包:https://dev.mysql.com/downloads/

    

    

    

  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的详细步骤(IDEA版本)的文章就介绍到这了,更多相关Java连接MySQL8.0 JDBC内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

[!--infotagslink--]

相关文章