一.匯入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(); } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/272158.html
標籤:MySQL
上一篇:求解
