IDEA中連線、使用MySQL
JDBC(重點)
資料庫驅動
我們的程式會通過資料庫驅動,和資料庫打交道!
就會通過資料庫驅動與資料庫相關聯
JDBC
SUN公司為了簡化開發人員的(對資料庫的統一)操作,提供了一個(Java操作資料庫的)規範,俗稱:JDBC
這些規範的實現由具體的廠商去做。
對於開發人員來說,我們只需要
java.sql
javax.sql
還需要匯入一個數據庫驅動包
第一個JDBC程式
建立測試資料庫
CREATE DATABASE jdbcStudy CHARACTER SET utf8 COLLATE utf8_general_ci; USE jdbcStudy; CREATE TABLE `users`( id INT PRIMARY KEY, NAME VARCHAR(40), PASSWORD VARCHAR(40), email VARCHAR(60), birthday DATE ); INSERT INTO `users`(id,NAME,PASSWORD,email,birthday) VALUES(1,'zhansan','123456','[email protected]','1980-12-04'), (2,'lisi','123456','[email protected]','1981-12-04'), (3,'wangwu','123456','[email protected]','1979-12-04')
-
建立一個普通專案
-
匯入資料庫驅動(建立一個lib資料夾匯入jar檔案–>右鍵檔案Add as Library)
-
編寫測試程式碼
package lijinyu.lesson01; import java.sql.*; //我的第一個JDBC程式 public class JdbcFirstDemo { public static void main(String[] args) throws ClassNotFoundException, SQLException { //1 載入驅動 Class.forName("com.mysql.jdbc.Driver"); //固定寫法 載入驅動 //2. 使用者資訊和url //useUnicode=true&characterEncoding=utf8&useSSL=true String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&&characterEncoding=utf8&&useSSL=false"; String username="root"; String password="ljy123456"; // 3.連線成功,資料庫物件 connection 代表資料庫 Connection connection = DriverManager.getConnection(url, username, password); //4. 執行SQL的物件 Statement 執行SQL的物件 Statement statement = connection.createStatement(); // 5. 執行SQL的物件 去 執行SQL ,可能存在結果 ,檢視返回結果 String sql="SELECT * FROM `users`"; ResultSet resultSet = statement.executeQuery(sql); // 返回的結果集,結果集中封裝了我們全部的查詢出來的結果 while (resultSet.next()){ System.out.println("id="+ resultSet.getObject("id")); System.out.println("name="+ resultSet.getObject("NAME")); System.out.println("pwd="+ resultSet.getObject("PASSWORD")); System.out.println("email="+ resultSet.getObject("email")); System.out.println("birth="+ resultSet.getObject("birthday")); } // 6. 釋放連線 resultSet.close(); statement.close(); connection.close(); } }
步驟總結:
- 載入驅動
- 連線資料庫DriverManager
- 獲得執行sql的物件 Statement
- 獲得返回的結果集
- 釋放連線
DriverManager
Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection(url, username, password); //connection 代表資料庫 // 資料庫設定自動提交 //事務提交 //事務回滾 connection.rollback(); connection.commit(); connection.setAutoCommit();
URL
String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
// mysql---3306
//協議: jdbc:mysql://主機地址:埠號/資料庫名?引數1&引數2&引數3
//oralce -- 1521
//jdbc:oracle:thin:@localhost:1521:sid
Statement執行SQL的物件,PrepareStatement執行SQL的物件
String sql = “SELECT * FROM users”; // 編寫SQL
statement.execute(); //執行任何SQL
statement.executeQuery(); //查詢操作返回ResultSet
statement.executeUpdate(); // 更新、插入、刪除,都是用這個,返回一個受影響的行數
ResultSet 查詢的結果集,封裝了所有的查詢結果
獲得指定的資料型別
resultSet.getobject(); // 在不知道列型別的情況下使用
//如果知道列的型別就使用特定的型別
resultSet.getstring()
resultSet.getin()
...
遍歷,指標
resulSet.beforeFirst(); //移動到最前面
resulSet.afterLast(); // 移動到最後
resulSet.next(); // 移動到下一個資料
resulSet.previous(); // 移動到前一行
resulSet.absolute(row); //移動到指定行
釋放資源
//6.釋放連線
resultSet.close();
statement.close();
connection.close(); //耗資源,用完關掉!
statement物件
jdbc中的statement物件用於向資料庫傳送SQL語句,想完成對資料庫的增刪改查,只需要通過這個物件向資料庫傳送增刪改查語句即可。
Statement物件的executeUpdate方法,用於向資料庫傳送增、刪、改的sql語句,executeUpdate執行完後,將會返回一個整數(即增刪改語句導致了資料庫幾行資料發生了變化)。
Statement.executeQuery方法用於向資料庫傳送查詢語句,executeQuery方法返回代表查詢結果的ResultSet物件。
CRUD操作-create
使用executeUpdate(String sql)方法完成資料新增操作:
Statement st =conn.createStatement();
String sql = "insert into user(...) values(...)";
int num = st.executeUpdate(sql);
if(num>0){
System.out.println("插入成功!");
}
同理 delete update也是一樣 只是sql不一樣
CRUD操作-read
使用executeQuery方法來完成資料查詢的操作
statement st= conn.createStatement();
String sql="select * from user where id =1";
ResultSet rs =st.execute(sql);
while(rs.next()){
//根據獲取列的資料型別,分別呼叫rs的相應方法對映到java物件中
}
程式碼實現
提取工具類
package lijinyu.lesson02.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
try {
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
// 1.驅動只用載入一次
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
// 獲取連線
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
//釋放連線資源
public static void release(Connection connection, Statement st, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
編寫增刪改的方法 executeUpdate
package lijinyu.lesson02;
import lijinyu.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestInsert {
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); //獲取資料庫連線
st = conn.createStatement(); //獲得sql的執行物件
String sql = "insert into users(`id`,`name`,`password`) values(54,'ljy','8453')";
int i = st.executeUpdate(sql);
if (i > 0) {
System.out.println("插入成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}
package lijinyu.lesson02;
import lijinyu.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestDelete {
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); //獲取資料庫連線
st = conn.createStatement(); //獲得sql的執行物件
String sql = "delete from `users` where id = 4";
int i = st.executeUpdate(sql);
if (i > 0) {
System.out.println("刪除成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}
package lijinyu.lesson02;
import lijinyu.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestUpdate {
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection(); //獲取資料庫連線
st = conn.createStatement(); //獲得sql的執行物件
String sql = "update users set `name`='ljy',`email`='[email protected]' where id=1";
int i = st.executeUpdate(sql);
if (i > 0) {
System.out.println("修改成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}
查詢
package lijinyu.lesson02;
import lijinyu.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestSelect {
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
// 1. 獲取連線
try {
conn = JdbcUtils.getConnection();
// 2. 獲取執行物件
st = conn.createStatement();
//SQL語句
String sql = "select * from users where id =1";
rs = st.executeQuery(sql); //查詢完畢。會返回一個結果集
while (rs.next()) {
System.out.println(rs.getString("NAME"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}
SQL注入的問題
sql存在漏洞,會被攻擊導致資料洩露 SQL會被拼接 or
package lijinyu.lesson02;
import lijinyu.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQL注入 {
public static void main(String[] args) {
// 正常登入
// login("ljy","123456");
login(" ' or'1=1", "'or'1=1");
}
//登入業務
public static void login(String username, String password) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
// 1. 獲取連線
try {
conn = JdbcUtils.getConnection();
// 2. 獲取執行物件
st = conn.createStatement();
//select * from users where `name`='ljy` and `password` = '123456';
//select * from users where `name`='' or '1=1' and `password`='or'1=1 ;
String sql = "select * from users where `NAME`='" + username + "'AND `password`='" + password + "'";
rs = st.executeQuery(sql); //查詢完畢。會返回一個結果集
while (rs.next()) {
System.out.println(rs.getString("NAME"));
System.out.println(rs.getString("password"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}
PreparedStatement物件
PreparedStatement可以防止SQL注入,效率更高!
新增
package lijinyu.lesson03;
import lijinyu.lesson02.utils.JdbcUtils;
import java.util.Date;
import java.sql.*;
public class TestInsert {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
//區別
//使用問號 ? 佔位符代替引數
String sql = "insert into users(`id`,`name`,`password`,`birthday`) values(?,?,?,?)";
st = conn.prepareStatement(sql); //預編譯SQL,先寫SQL,然後不執行
//手動給引數賦值
//set(x,x) 第一個x代表第幾個? 第2個x代表具體的賦值
st.setInt(1, 5); //id賦值
st.setString(2, "lijiynu");
st.setString(3, "123456789987");
//注意點:sql.date 資料庫
// util.date java new Date().getTime() 獲得時間戳
st.setDate(4, new java.sql.Date(new Date().getTime()));
//執行
int i = st.executeUpdate();
if (i > 0) {
System.out.println("插入成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.release(conn, st, null);
}
}
}
刪除
package lijinyu.lesson03;
import lijinyu.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class TestDelete {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
//區別
//使用問號 ? 佔位符代替引數
String sql = "delete from users where id =?";
st = conn.prepareStatement(sql); //預編譯SQL,先寫SQL,然後不執行
//手動給引數賦值
st.setInt(1, 5);
//執行
int i = st.executeUpdate();
if (i > 0) {
System.out.println("刪除成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.release(conn, st, null);
}
}
}
更新
package lijinyu.lesson03;
import lijinyu.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestUpdate {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
//區別
//使用問號 ? 佔位符代替引數
String sql = "update users set `name` = ? where `id`=? ;";
st = conn.prepareStatement(sql); //預編譯SQL,先寫SQL,然後不執行
//手動給引數賦值
st.setString(1, "李四");
st.setInt(2, 1);
//執行
int i = st.executeUpdate();
if (i > 0) {
System.out.println("更新成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.release(conn, st, null);
}
}
}
查詢
package lijinyu.lesson03;
import lijinyu.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestSelect {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "select * from users where id =?";
st = conn.prepareStatement(sql); //預編譯
st.setInt(1, 1); //傳遞引數
//執行
rs = st.executeQuery();
if (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}
防止SQL注入
package lijinyu.lesson03;
import lijinyu.lesson02.utils.JdbcUtils;
import java.sql.*;
public class SQL注入 {
public static void main(String[] args) {
// 正常登入
login("李四", "123456");
// login(" '' or 1=1", "123456");
}
//登入業務
public static void login(String username, String password) {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
// 1. 獲取連線
try {
conn = JdbcUtils.getConnection();
//PreparedStatement放注入的本質:把傳遞進來的引數當作字元
//假設其中存在轉義字元,就直接忽略,’會被直接轉義
String sql = "SELECT * FROM `users` WHERE `NAME`= ? AND `PASSWORD`=?";
st = conn.prepareStatement(sql);
st.setString(1, username);
st.setString(2, password);
rs = st.executeQuery(sql); //查詢完畢。會返回一個結果集
while (rs.next()) {
System.out.println(rs.getString("NAME"));
System.out.println(rs.getString("password"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}
使用IDEA連線資料庫
連線mysql
選擇資料庫
查詢資料庫資訊
更新資訊
這裡步驟二就是提交資訊的意思
建立控制檯 寫SQL語句
表示切換資料庫
如果連線資料庫失敗
![\[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-E7xlRi1s-1608174652994)(C:%5CUsers%5CAdministrator%5CAppData%5CRoaming%5CTypora%5Ctypora-user-images%5Cimage-20201216193544304.png)\]](https://www.icode9.com/img/ll/?i=20201217111355747.png?,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl81MTQxODU3Mg==,size_16,color_FFFFFF,t_70)
在這裡修改改資料庫對應的版本SQL
JDBC操作事務
要麼都成功,要麼都失敗
ACID原則
原子性:要麼全部完成,要麼都不完成
一致性:結果總數不變
隔離性:多個程序互不干擾
永續性: 一旦提交不可逆,持久化到資料庫了。
隔離性的問題:
髒讀:一個事務讀取了另一個沒有提交的事務
不可重複讀:在同一個事務內,重複讀取表中的資料,表資料發生了改變(不知道用原來的資料還是現在的資料)
虛度(幻讀):在一個事務內,讀取到了別人插入的資料,導致了前後讀出來的結果不一致
程式碼實現
- 開啟事務
conn.setAutoCommit(false)
- 一組事務執行完畢,提交事務
- 可以在catch語句中顯示的定義 回滾語句,但是預設失敗就會回滾
package lijinyu.lesson04;
import lijinyu.lesson02.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
// JDBC中的事務
public class TestTransaction {
public static void main(String[] args) {
Connection conn =null;
PreparedStatement st =null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
//關閉資料庫的自動提交功能,自動會開啟事務
conn.setAutoCommit(false); // 開啟事務
String sql1="update account set money = money-100 where name='A'";
st = conn.prepareStatement(sql1);
st.executeUpdate();
String sql2="update account set money = money+100 where name='B'";
st = conn.prepareStatement(sql2);
st.executeUpdate();
//業務完畢,提交事務
conn.commit();
System.out.println("更新成功");
} catch (SQLException throwables) {
try {
conn.rollback(); //如果失敗則回滾事務
} catch (SQLException e) {
e.printStackTrace();
}
throwables.printStackTrace();
}finally {
JdbcUtils.release(conn,st,rs);
}
}
}
資料庫連線池
資料庫連線–執行完畢 --釋放
連線–釋放 十分浪費系統資源
池化技術:準備一些預先的資源,過來就連線預先準備好的
— 開門–業務員:等待 – 服務 --‘
15個業務員
最小連線數:10
最大連線數:15 業務最高承載上限
等待超時:100ms
編寫連線池,實現一個介面: DataSource
開源資料來源實現(拿來即用)
DBCP
C3P0
Druid:阿里巴巴
使用了這些資料庫連線池之後,我們在專案開發中就不需要編寫連線資料庫的程式碼了!
DBCP
需要用到的jar包:
commons-dbcp-1.4、commons-pool-1.6
C3P0
c3p0-0.9.5.5 、mchange-commons-java-0.2.19
結論
無論使用什麼資料來源,本質還是一樣,DataSource介面不會變,方法就不會變