目錄
一、加載并注冊數(shù)據(jù)庫驅(qū)動程序
二、通過DriverManager獲取數(shù)據(jù)庫連接
三、通過Connection對象獲取Statement對象
四、使用Statement執(zhí)行SQL語句
五、操作結(jié)果集
六、關(guān)閉連接并釋放資源
具體操作:
1、搭建數(shù)據(jù)庫環(huán)境(百度網(wǎng)盤數(shù)據(jù)庫5.7版本鏈接:https://pan.baidu.com/s/1oaGYqzgjy5wIJXEVaqruAA?pwd=gx5q?
提取碼:gx5q。其他版本可以去oracle官網(wǎng)下載。)
? ? 在MySQL中創(chuàng)建名稱為jdbc的數(shù)據(jù)庫,然后在jdbc數(shù)據(jù)庫中創(chuàng)建users表,創(chuàng)建數(shù)據(jù)庫和表的SQL語句如下(注:一個分號為一條語句,所有的標點符號都要用英文格式,否則會報錯)
jdbc數(shù)據(jù)庫和users表創(chuàng)建成功后,再向users表中插入3條數(shù)據(jù),SQL語句如下
使用select語句查看users表中的數(shù)據(jù)
?2、創(chuàng)建環(huán)境變量
(1)在idea中新建項目
(2)右鍵New->Directory,命名為lib
?(3)File->Project Structure->Modules->Dependencies,點擊+號,選擇JARs or directories,選擇mysql-connector的安裝路徑。
(mysql-connector百度網(wǎng)盤提取鏈接:https://pan.baidu.com/s/1ACl7-GslKhnxIHhcNugi8g?pwd=86ej?
提取碼:86ej)
?(4)將mysql-connector-java-8.0.25添加到依賴之后,點擊apply,再單擊OK。加入數(shù)據(jù)庫驅(qū)動程序后的項目結(jié)構(gòu)如下
三、編寫jdbc程序
在新建的DataBaseConetion的src目錄下新建一個com.itheima.jdbc.example的包(package),在該包中創(chuàng)建Example01類,該類用于讀取數(shù)據(jù)庫中的users類,并將結(jié)果輸出到控制臺。
文章來源:http://www.zghlxwxcb.cn/news/detail-754454.html
?源碼如下:文章來源地址http://www.zghlxwxcb.cn/news/detail-754454.html
package com.itheima.jdbc.example; import java.sql.*; public class Example01 { public static void main(String[] args) throws Exception{ Statement stmt=null; ResultSet rs=null; Connection conn=null; try{ //1.注冊數(shù)據(jù)庫的驅(qū)動程序 Class.forName("com.mysql.jdbc.Driver");//MYSQL 6.0.2版本之后的為Class.forName("com.mysql.cj.jdbc.Driver"); //2.通過DriverManager獲取數(shù)據(jù)庫連接 String ur1="jdbc:mysql://localhost:3306/jdbc"+"?serverTimezone=GMT%2B8&UseSSL=false"; String username="root"; //數(shù)據(jù)庫用戶名 String password="******"; //數(shù)據(jù)庫密碼 conn=DriverManager.getConnection(ur1,username,password); //3.通過Connection對象獲取Statement對象 stmt=conn.createStatement(); //4.使用Statement執(zhí)行SQL語句 String sql="select * from users"; rs= stmt.executeQuery(sql); //5.操作結(jié)果數(shù) System.out.println("id | name | password"+"| email | birthday"); while(rs.next()){ int id=rs.getInt("id");//通過列名獲取指定列的值 String name=rs.getNString("name"); String psw= rs.getNString("password"); String email= rs.getNString("email"); Date birthday=rs.getDate("birthday"); System.out.println(id+" |"+name+" | "+psw+" | "+email+" | " +birthday); } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } finally { //6.回收數(shù)據(jù)庫資源 if(rs!=null){ try{ rs.close(); }catch (SQLException e){ e.printStackTrace(); } stmt=null; } if(conn!=null){ try{ conn.close(); }catch (SQLException e){ e.printStackTrace(); } conn=null; } } } }
到了這里,關(guān)于在idea中實現(xiàn)數(shù)據(jù)庫的連接的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!