JDBC使用步驟:
create database jdbctest;
use jdbctest;
create table user(
id int unsigned auto_increment key,
username varchar(20),
password varchar(20),
name varchar(20)
);
insert into user values(null, 'aaa', '111', '張三'),
(null, 'bbb', '222', '李四'),
(null, 'ccc', '333', '王五');
DriverManager.registerDriver(new Driver());
2、 獲得連接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "wxhxx520");
3、 創建執行SQL語句的對象,並執行SQL
a) 創建sql語句,獲得statement對象
String sql = “select * from user”;
Statement stmt = conn.createStatement();
b) 執行sql語句
ResultSet resultSet = stmt.executeQuery(sql);
while(resultSet.next()){
// int id = resultSet.getInt(1);
// String username = resultSet.getString(2);
// String password = resultSet.getString(3);
// String name = resultSet.getString(4);
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
String password = resultSet.getString("password");
String name = resultSet.getString("name");
System.out.println(id + " " + username + ":" + password + " " + name);
}
4、 釋放資源
resultSet.close();
statement.close();
conn.close();
完整程序:
package com.luyue.jdbc;
import com.mysql.jdbc.Driver;
import org.junit.jupiter.api.Test;
import java.sql.*;
public class JDBC_Demo {
@Test
public void demo(){
try {
//1、加載驅動
DriverManager.registerDriver(new Driver());
//2、獲得連接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "wxhxx520");
//3、創建執行SQL語句的對象,並且執行SQL
//3.1創建sql語句,獲得Statement對象
String sql = "select * from user";
Statement statement = conn.createStatement();
//3.2執行sql語句
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
// int id = resultSet.getInt(1);
// String username = resultSet.getString(2);
// String password = resultSet.getString(3);
// String name = resultSet.getString(4);
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
String password = resultSet.getString("password");
String name = resultSet.getString("name");
System.out.println(id + " " + username + ":" + password + " " + name);
}
//4、釋放資源
resultSet.close();
statement.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
JDBC 的API介紹:
DriverManager:驅動管理類
a) 註冊驅動
DriverManager.registerDriver(new Driver());//這種方法註冊的驅動實質上註冊了兩次
源碼分析:
靜態代碼塊中調用了DriverManager已經註冊了,而靜態代碼塊在類加載時執行,而我們的代碼中又手動的調用了一次,實質上註冊兩次。
另一種調用方法(實際開發中的註冊方法):
Class.forName(“com.mysql.jdbc.Driver”);//加載Driver類,則靜態代碼塊執行,則驅動註冊。
b) 獲得連接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "wxhxx520");
url寫法:jdbc:mysql://localhost:3306/jdbctest
其中jdbc:協議
mysql:子協議
localhost:主機名
3306:端口號
連接本機數據庫的另一種寫法:
“jdbc:mysql:// /jdbctest”//中間部分省略掉
Connection:連接對象
a) 創建用來執行sql語句的對象
Statement statement = conn.createStatement(); //可以用來執行sql語句,但是有sql注入漏洞存在
prepareStatement ps= conn .prepareStatement(String sql)//預編譯sql語句,解決sql注入漏洞
CallableStatement cs = conn.prepareCall(String sql)//執行sql中存儲過程
b) 進行事務的管理
setAutoCommit(boolean autoCommit) //設置事務是否自動提交
commit()//事務提交
rollback()//事務回滾
Statement:執行sql語句
a) 執行sql語句boolean execute(String sql)//執行sql,執行select返回true,否則false
ResultSet executeQuery(String sql)//執行sql中的select語句
int executeUpdate(String sql) //執行sql中的insert/update/delete語句
b) 執行批處理操作:
addBatch(String sql)//將sql語句添加到批處理
int[] executeBatch()//執行批處理
clearBatch()//清除批處理
ResultSet:結果集,對select查詢結果的一個封裝
a) 常用方法:
boolean next() //移動光標,一開始的光標在真正數據之前,用來判斷下一行是否有數據,如果有則指向下一行
針對不同類型數據使用getxxx()方法獲取數據
Object getObject(String columnLabel) //通用方法
Eg:
CREATE TABLE goods(
id int unsigned auto_increment key comment '商品編號',
name varchar(20) unique not null comment '商品名稱',
price float(7,1) not null default 0.0 comment '商品價格',
desp varchar(100) not null comment '商品描述'
);
insert goods() values(null, '手機', 2000.0, '黑色,存儲32G'),
(null, '冰箱', 1500.0, '銀色,對開門'),
(null, '洗衣機', 3000.0, '滾動'),
(null, '空調', 4000, '變頻空調');
public class JDBC_Demo2_11 {
//查詢價格在3500以下的商品信息,並在控制檯打印輸出。
@Test
public void demo(){
//1、註冊驅動
try {
//1、註冊驅動
Class.forName("com.mysql.jdbc.Driver");
//2、獲得連接
Connection conn = DriverManager.getConnection("jdbc:mysql:///jdbctest", "root", "wxhxx520");
//3、獲得statement對象,並執行sql語句
String sql = "select * from goods where price<=3500";
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
float price = resultSet.getFloat("price");
String desp = resultSet.getString("desp");
System.out.println(id + " " + name + " " + price + " " + desp);
}
//4、釋放連接
resultSet.close();
statement.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
JDBC資源釋放:
Jdbc程序運行完後,要釋放程序在運行過程中創建的那些與數據庫交互的對象,通常是:
ResultSet, Statement, Connection
特別是Connection,它是非常稀有的資源,用完後要馬上釋放,若不及時釋放,極易導致系統宕機。使用原則:晚創建,早釋放
其中爲確保釋放的代碼能夠正常運行,資源釋放代碼要放在finally語句中
Eg:依舊是上述代碼,改變之後的標準釋放過程:
public class JDBC_Demo2_11 {
//查詢價格在3500以下的商品信息,並在控制檯打印輸出。
@Test
public void demo(){
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
//1、註冊驅動
try {
//1、註冊驅動
Class.forName("com.mysql.jdbc.Driver");
//2、獲得連接
conn = DriverManager.getConnection("jdbc:mysql:///jdbctest", "root", "wxhxx520");
//3、獲得statement對象,並執行sql語句
String sql = "select * from goods where price<=3500";
statement = conn.createStatement();
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
float price = resultSet.getFloat("price");
String desp = resultSet.getString("desp");
System.out.println(id + " " + name + " " + price + " " + desp);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//4、釋放連接
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
resultSet = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null//多手動設置一次null的原因是爲了垃圾回收機制能夠更早的回收;
}
}
}
}