JDBC(連接數據庫)
簡單連接數據庫的步驟:
1、將mysql的jdbc驅動加載到內存中
指定需要連接的數據庫地址、用戶名和密碼;
2、獲取連接;
3、通過連接創建Statement對象;
4、執行數據庫(DML);
jdbc 中增、刪、改都是executeUpdate方法
5、關閉數據庫;
代碼詳情如下:
package com.yj.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class Test { public static void main(String[] args) { // 1、將mysql的jdbc驅動加載到內存中 try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } //指定需要連接的數據庫地址,用戶和密碼 String url = "jdbc:mysql://127.0.0.1:3306/bus"; String user = "root"; String password = "123456"; Connection conn = null; Statement stmt = null; try { // 2、獲取鏈接 conn = DriverManager.getConnection(url,user,password); // 3、通過連接創建statement對象 stmt = conn.createStatement(); // 4、執行數據庫語句 //jdbc中增、刪、改都是executeUpdate方法 //這個方法會返回一個int類型的值 //對應就是幾行數據受影響 //插入(增加)語句 int n = stmt.executeUpdate("insert into t_user(username,userpwd,tel,address,sex)values('333','222','222','1211111112','男')"); //刪除語句 //int n = stmt.executeUpdate("delete from t_user where sex='男'"); //修改語句 //int n = stmt.executeUpdate("update t_user set sex='女',address='綿陽',tel='13888888888' where u_pk_id=1"); System.out.println(n + "個受影響"); } catch (SQLException e) { e.printStackTrace(); }finally { // 5、關閉數據庫 try { if (stmt != null) { stmt.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (conn !=null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }