一、下載MySQL數據庫並進行安裝和配置
二、下載JDBC
下載地址:https://dev.mysql.com/downloads/connector/j/5.1.html
三、創建java項目,導入.jar包
四、測試訪問數據庫
1.使用JDBC API 連接和訪問數據庫,一般分為以下5個步驟
(1)加載驅動程序
(2)建立連接對象
(3)創建語句對象
(4)獲得SQL語句的執行結果
(5)關閉建立的對象,釋放資源
2.例如下面訪問數據庫的代碼
(1)首先使用Navicat連接MySQL數據庫,並在localhost新建如下圖所示的數據庫和表
特別注意
(2)在IDEA中新建類,並編寫如下的程序
import java.sql.*; public class MySQLDemo { public static void main(String[] args) throws Exception{ //加載數據庫驅動程序 try{ Class.forName("com.mysql.cj.jdbc.Driver"); }catch (ClassNotFoundException cne){ cne.printStackTrace(); } String dburl = "jdbc:mysql://127.0.0.1:3306/webstore?&useSSL=false&serverTimezone=UTC"; String sql = "SELECT * FROM products where id < 104"; try( Connection conn = DriverManager.getConnection(dburl,"root","123456"); Statement stmt = conn.createStatement(); ResultSet rst = stmt.executeQuery(sql)) { while (rst.next()){ System.out.println(rst.getInt(1)+"\t"+ rst.getString(2)+"\t"+rst.getString(3)+ "\t"+rst.getFloat(4) + "\t" + rst.getInt(5) ); } }catch (SQLException se){ se.printStackTrace(); } } }
(3)運行結果如下圖所示