首页 > 数据库技术 > 详细

Java连接MySQL8.0——JDBC(IDEA版本)

时间:2021-04-04 01:07:44      阅读:38      评论:0      收藏:0      [点我收藏+]

一.导入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版本)

原文:https://www.cnblogs.com/lofun/p/14615428.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!