JDBC
1.JDBC簡介
定義了操作所有關係型數據庫的規則
作用:用java語言操作數據庫
本節用到的架構:
JDBC的核心API
接口或類 | 作用 |
---|---|
DriverManger類 | 1.管理與註冊數據庫驅動 2.得到數據庫連接對象 |
Connection接口 | 連接對象,用於創建Statement和PreparedStatement對象 |
Statement接口 | SQL語句對象,用於將SQL語句發送給數據庫服務器 |
PreparedStatement接口 | SQL語句對象,Statement的子接口 |
ResultSet接口 | 封裝數據庫查詢到的結果集,返回給java程序 |
JDBC使用步驟:
- 導入驅動jar包
- 註冊驅動
- 獲取數據庫連接對象 (Connection,DriverManager)
- 定義sql語句
- 獲取執行sql的對象 (Statement)
- 執行sql
- 處理結果
- 釋放資源
實現代碼
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class JDBCDemo1 {
public static void main(String[] args) throws Exception {
//註冊驅動
Class.forName("com.mysql.jdbc.Driver");
//獲取數據庫連接對象connection
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/Student","root","root");
//sql語句
String sql = "update class_1 set math = 60 where id < 3";
//獲取執行sql語句的對象statement
Statement statement = connection.createStatement();
//執行sql語句,返回影響的行數
int count = statement.executeUpdate(sql);
System.out.println(count);
//釋放資源
connection.close();
statement.close();
}
}
詳解各個對象
- DriverManager:驅動管理對象
- Connection:數據庫連接對象
- Statement:執行sql的對象
- ResultSet:結果集對象
- PreparedStatement:執行sql的對象
2.DriverManager類
驅動管理對象
功能:
- 註冊驅動:告訴程序使用哪一個數據庫驅動jar包
方法:static void registerDriver(Driver driver)
:
功能:註冊與給定驅動程序DriverManager。
寫代碼使用:Class.forName("com.mysql.jdc.Driver");
注意:mysql 1.5之後的jar包可以省略註冊驅動的步驟
- 獲取數據庫連接
方法:static Connection getConnection(String url,String user,String password)
參數:
- url :指定連接的路徑
- 語法:jdbc:mysql://ip地址(域名):端口號/數據庫名稱
- 例子:jdbc:mysql://localhost:3306/Student
- 如果連接的是本機mysql服務器,並且mysql默認服務端口是3306,則url簡寫爲:jdbc:mysql:///數據庫名稱
- user:用戶名
- password:密碼
3.Connection接口
數據庫連接對象
功能:
-
獲取執行sql的對象
Statement createStatement()
PreparedStatement prepareStatement(String sql)
-
管理事務
-
開啓事務:
setAutoCommit(boolean autoCommit)
調用該方法設置參數爲false,即開啓事務
-
提交事務:
commit()
-
回滾事務:
rollback()
-
4.Statement接口
執行sql的對象
方法聲明 | 功能描述 |
---|---|
boolean execute(String sql) | 執行任意的sql |
int executeUpdate(String sql) | 執行DML與DDL語句,返回影響行數,返回值<0則失敗 |
ResultSet executeQuery(String sql) | 執行DQL語句 |
5.ResultSet接口
結果集對象,封裝查詢結果
-
boolean next()
:遊標向下移動一行,判斷當前行是否是最後一行,如果是,返回false,如果不是,返回true。 -
getXxx(參數)
:獲取數據- Xxx:代表數據類型 eg:int getInt(),String getString()
- 參數:
- int:代表列的編號,從1開始
- String:代表列名稱
實例代碼1
import java.util.Date;
/*將class_1表的封裝成類*/
@SuppressWarnings("all")
public class Class_1 {
private int id;
private String name;
private int age;
private String classroom;
private double english;
private double chinese;
private double math;
private Date recordtime;
private int lesson;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getClassroom() {
return classroom;
}
public void setClassroom(String classroom) {
this.classroom = classroom;
}
public double getEnglish() {
return english;
}
public void setEnglish(double english) {
this.english = english;
}
public double getChinese() {
return chinese;
}
public void setChinese(double chinese) {
this.chinese = chinese;
}
public double getMath() {
return math;
}
public void setMath(double math) {
this.math = math;
}
public Date getRecordtime() {
return recordtime;
}
public void setRecordtime(Date recordtime) {
this.recordtime = recordtime;
}
public int getLesson() {
return lesson;
}
public void setLesson(int lesson) {
this.lesson = lesson;
}
@Override
public String toString() {
return "Class_1{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", classroom='" + classroom + '\'' +
", english=" + english +
", chinese=" + chinese +
", math=" + math +
", recordtime=" + recordtime +
", lesson=" + lesson +
'}';
}
}
實例代碼2
/*
* 需求:查詢class_表中的信息
* */
public class JDBCDemo1 {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
Class_1 class_1;
List<Class_1> list = new ArrayList<>();
public static void main(String[] args) {
List<Class_1> all = new JDBCDemo1().findAll();
for (Class_1 person : all) {
System.out.println(person);
}
}
public List<Class_1> findAll(){
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/Student","root","root");
statement = connection.createStatement();
String sql = "select * from class_1";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
//將數據庫裏的數據記錄提取出來
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String classroom = resultSet.getString("class");
double english = resultSet.getDouble("english");
double chinese = resultSet.getDouble("chinese");
double math = resultSet.getDouble("math");
Date recordtime = resultSet.getDate("recordtime");
int lesson = resultSet.getInt("lesson");
//創建表類對象
class_1 = new Class_1();
class_1.setId(id);
class_1.setName(name);
class_1.setAge(age);
class_1.setClassroom(classroom);
class_1.setEnglish(english);
class_1.setChinese(chinese);
class_1.setMath(math);
class_1.setRecordtime(recordtime);
class_1.setLesson(lesson);
list.add(class_1);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e){
e.printStackTrace();
}finally {
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
}
6.JDBC工具類:JDBCUtils
作用:簡化書寫
實例代碼
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
static {
try {
//創建Properties集合類
Properties properties = new Properties();
//獲取src路徑下的文件方式
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL resource = classLoader.getResource("mysql.properties");
String path = resource.getPath();
//加載文件
properties.load(new FileReader(path));
//獲取數據,賦值
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
driver = properties.getProperty("driver");
//註冊驅動
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 獲取連接
* @return連接對象
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
/**
* 釋放資源
* @param connection
* @param statement
* @param resultSet
*/
public static void close(Connection connection, Statement statement, ResultSet resultSet){
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
properties文件
url = jdbc:mysql://localhost:3306/Student
user = root
password = root
driver = com.mysql.jdbc.Driver
7.PreparedStatement接口
Statement接口的子接口
作用:執行sql的對象,解決SQL注入問題
- SQL注入問題:在拼接sql時,有一些sql的特殊關鍵字參與字符串的拼接。會造成安全性問題
- 預編譯的SQL:參數?作爲佔位符
- 解決方式:
- 導入驅動jar包
- 註冊驅動
- 獲取數據庫連接對象 (Connection,DriverManager)
- 定義sql
- 注意:sql的參數使用?作爲佔位符
- 獲取執行sql的對象 (PrepareStatement)
- 給?傳值
- 方法:setXxx(參數1,參數2)
- 參數1:?的位置編號從1開始
- 參數2:?的值
- 方法:setXxx(參數1,參數2)
- 執行sql,接受返回結果,不需要傳遞sql語句
- 處理結果
- 釋放資源
注意:後期都會使用PreparedStatement來完成增刪改查的所有操作
實例代碼
import Utils.JDBCUtils;
import java.sql.*;
import java.util.Scanner;
@SuppressWarnings("all")
public class JDBCDemo2 {
String user,password;
Connection connection = null;
PreparedStatement ppst = null;
ResultSet resultSet = null;
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入用戶名:");
String user = scanner.nextLine();
System.out.println("請輸入密碼");
String password = scanner.nextLine();
boolean flag = new JDBCDemo2().login(user, password);
System.out.println(flag ? "登錄成功":"用戶名或密碼錯誤");
}
public boolean login(String user,String password){
if(user == null || password == null){
return false;
}
try {
Connection connection = JDBCUtils.getConnection();
String sql = "select * from acount where user = ? and password = ?";
ppst = connection.prepareStatement(sql);
ppst.setString(1,user);
ppst.setString(2,password);
resultSet = ppst.executeQuery();
return resultSet.next();
} catch (SQLException e) {
e.printStackTrace();
}finally{
JDBCUtils.close(connection,ppst,resultSet);
}
return false;
}
}
8.JDBC控制事務
事務:一個包含多個步驟的業務操作。如果這個業務操作被事務管理,則這多個步驟要麼同時成功,要麼同時失敗。
操作:
- 開啓事務
- 提交事務
- 回滾事務
使用Connection對象來管理事務
- 開啓事務:
setAutoCommit(boolean autoCommit)
:調用該方法設置參數爲false,即開啓事務- 在執行sql之前開啓事務
- 提交事務:
commit()
- 當所有sql都執行完提交事務
- 回滾事務:
rollback()
- 在catch中回滾事務
實例代碼
import Utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@SuppressWarnings("all")
public class JDBCDemo3 {
Connection connection = null;
PreparedStatement ppst1 = null,ppst2 = null;
public static void main(String[] args) {
new JDBCDemo3().transfer();
}
public void transfer(){
try {
connection = JDBCUtils.getConnection();
connection.setAutoCommit(false);
String sql1 = "update account set balance = balance - ? where name = ?";
String sql2 = "update account set balance = balance + ? where name = ?";
ppst1 = connection.prepareStatement(sql1);
ppst2 = connection.prepareStatement(sql2);
ppst1.setInt(1,500);
ppst1.setString(2,"Lisi");
ppst2.setInt(1,500);
ppst2.setString(2,"AFan");
ppst1.executeUpdate();
ppst2.executeUpdate();
connection.commit();
} catch (Exception e) {
e.printStackTrace();
if(connection!=null){
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}finally {
JDBCUtils.close(connection,ppst1);
JDBCUtils.close(null,ppst2);
}
}
}
9.數據庫連接池
概念:容器(集合),存放數據庫連接的容器。當系統初始化好後,容器中會申請一些連接對象,當用戶來訪問數據庫時,從容器中獲取連接對象,用戶訪問完之後,會將連接對象歸還給容器。
優點:
- 節約資源
- 用戶訪問高效
DataSource接口
javax.sql包下的
方法:
方法聲明 | 功能描述 |
---|---|
Connection getConnection() | 獲取鏈接 |
void close() | 如果連接對象Connection是從連接池中獲取,則不會關閉連接,而是歸還連接。 |
此接口一般由數據庫廠商來實現
- c3p0:數據庫鏈接池技術
- Druid:數據庫連接池實現技術
c3p0
數據庫連接池技術
使用步驟:
- 導入jar包(兩個):
c3p0-0.9.5.2.jar
mchange-commons-java-0.2.12.jar
。- 注意:還要導入數據庫驅動jar包
- 定義配置文件
- 名稱: c3p0.properties 或者 c3p0-config.xml
- 路徑:直接將文件放在src目錄下
- 創建數據庫連接池對象
ComboPoolDataSource
- 獲取連接對象
getConnection()
//1.利用多態創建數據庫連接池對象
DataSource ds = new ComboPoolDataSource();
//2.獲取連接對象
Connection connection = ds.getConnection()
Druid
數據庫連接池技術,阿里巴巴提供
使用步驟:
-
導入jar包
druid-1.0.9.jar
-
定義配置文件:
- 是properties形式的
- 可以叫任意名稱,可以放在任意目錄下
-
加載配置文件
-
獲取數據庫連接池對象:通過工廠來獲取
DruidDataSourceFactory
-
獲取連接
getConnection()
//3.加載配置文件
Properties pro = new Properties();
InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//4.獲取連接池對象
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
Connection connection = ds.getConnection();
定義工具類
- 定義一個類JDBCUtils
- 提供靜態代碼塊加載文件,初始化連接池對象
- 提供方法
- 獲取連接方法:通過數據庫連接池獲取連接
- 釋放資源
- 獲取連接池的方法
JDBCUtils工具類實例代碼
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
@SuppressWarnings("all")
public class JDBCUtils {
private static DataSource ds = null;
static {
try {
//1.加載配置文件
Properties properties = new Properties();
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(is);
//2.獲取DataSource對象
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//獲取鏈接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//釋放資源
public static void close(Connection connection){
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection connection, Statement statement) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection connection, Statement statement, ResultSet resultSet){
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
10.JDBCTemplate類
Spring框架中對jdbc的簡單封裝
使用步驟:
使用步驟:
-
導入jar包
-
創建JdbcTemplate對象,依賴於數據源DataSource
JdbcTemplate template = new JdbcTemplate(ds)
-
JdbcTemplate方法來完成CRUD的操作
方法聲明 | 功能描述 |
---|---|
int update(String sql) | 執行DML語句 |
Map< String , Object > queryForMap(String sql) | 查詢結果將結果封裝爲map集合,列名爲key,將值作爲value將這條記錄封裝爲一個map集合,方法查詢的結果集長度和只能爲1 |
List<Map< String , Object > >queryForList(String sql) | 查詢結果將結果集封裝成list集合 |
List query(String sql,參數) | 查詢結果,將結果封裝爲JavaBean對象 參數:RowMapper類型,一般使用new BeanPropertyRowMapper<類型>(類型.class)完成數據到JavaBean的自動封裝 |
queryForObject(String sql,參數) | 查詢結果,將結果封裝成對象,一般用於聚合函數的查詢 |