MAC 中使用JDBC連線MySQL
阿新 • • 發佈:2020-11-30
- JDBC 全稱是 JAVA DataBase Connectivity(JAVA 語言連線資料庫)
- JDBC 的本質是一套介面,面向介面呼叫,面向介面寫實現類
面向介面程式設計:是為了解耦合,提高程式的擴充套件力
(多型機制就是非常經典的:面向抽象程式設計)
JDBC 程式設計六步:
- 註冊驅動(告訴 JAVA,即將要連線的是哪個品牌的資料庫)
- 獲取連線(表示 JVM的程序喝資料庫程序之間的通道打開了,屬於程序之間的通訊,使用完了要關閉)
- 獲取資料庫操作物件
- 執行 SQL 語句
- 處理查詢結果(只有上一步執行的是 select 語句的時候,才有結果)
- 釋放資源(因為 JAVA 喝資料庫屬於程序間的通訊,開啟後要關閉)
這是配置檔案:
DB_url=jdbc:mysql://localhost:3306/dbtest
username=root
password=rootroot
driver=com.mysql.cj.jdbc.Driver
步驟:
public class DBConnection { public static void main(String[] args) { //使用資源繫結器,繫結配置檔案 ResourceBundle bundle = ResourceBundle.getBundle("jdbctest"); String driver = bundle.getString("driver"); String url = bundle.getString("DB_url"); String username = bundle.getString("username"); String password = bundle.getString("password"); Statement statement = null; ResultSet resultSet = null; Connection connection = null; try { //1.註冊JDBC驅動 Class.forName("com.mysql.cj.jdbc.Driver"); //2.獲取資料庫連線 connection = DriverManager.getConnection(url, username, password); System.out.println("資料庫連線物件=" + connection); //3.對資料庫操作 //Statement 專門執行 sql 語句的 statement = connection.createStatement();//獲取操作資料庫的物件 String sql = "select * from bookinfo";//執行 sql resultSet = statement.executeQuery(sql);//執行資料庫語句獲取結果集 //int executeUpdate(insert/delete/update) while (resultSet.next()) { int bookid = resultSet.getInt("book_id"); String bookname = resultSet.getNString("booK_name"); BigDecimal price = resultSet.getBigDecimal("price"); Date publicdate = resultSet.getDate("public_date"); int store = resultSet.getInt("store"); System.out.println("圖書編號" + bookid); System.out.println("圖書名" + bookname); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e){ e.printStackTrace(); } finally { //4.關閉結果集,資料庫操作物件,資料庫連線 try { if (statement != null) { statement.close(); } }catch (SQLException e){ e.printStackTrace(); } try { if (connection != null) { connection.close(); } }catch (SQLException e){ e.printStackTrace(); } try { if (resultSet != null) { resultSet.close(); } }catch (SQLException e){ e.printStackTrace(); } } } }
url:統一資源定位符(網路中某個資源的絕對路徑)
包括:協議、IP、PORT、資源名