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

一.導入jar包java

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

     

    

     

   2.導入sql

    在項目文件夾下新建一個名爲lib的文件夾數據庫

    

     將下載好的jar包放入lib文件夾,而後右擊lib文件夾,選擇Add as Library...,而後點擊okurl

    

    

二.代碼部分spa

  1.加載驅動3d

    Class.forName("com.mysql.cj.jdbc.Driver");code

  2.用戶信息和urlserver

    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();
    }

}
相關文章
相關標籤/搜索