JDBC連接數(shù)據(jù)庫(kù)步驟及基本操作示例詳解
JDBC基本操作
create table user(
id int primary key auto_increment,
name varchar(50)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;JDBC概念
JDBC是一個(gè)獨(dú)立于特定數(shù)據(jù)庫(kù)管理系統(tǒng)、通用的SQL數(shù)據(jù)庫(kù)存取和操作的公共接口,定義了用來(lái)訪問(wèn)數(shù)據(jù)庫(kù)的標(biāo)準(zhǔn)的Java類(lèi)庫(kù)
連接步驟
- 加載驅(qū)動(dòng)
- 進(jìn)行數(shù)據(jù)庫(kù)連接
// 驅(qū)動(dòng)
private static final String DRIVER = "com.mysql.jdbc.Driver";
// 地址
private static final String URL = "jdbc:mysql://localhost:3306/test";
//用戶名
private static final String USER_NAME = "root";
// 密碼
private static final String PSW = "123456";
/**
* 獲取連接
*/
public static Connection getConnection(){
Connection conn = null;
try {
// 加載驅(qū)動(dòng)
Class.forName(DRIVER);
// 數(shù)據(jù)庫(kù)連接
conn = DriverManager.getConnection(URL,USER_NAME,PSW);
} catch (ClassNotFoundException e) {
System.out.println("加載驅(qū)動(dòng)失敗,請(qǐng)檢查是否引入Jar包或者驅(qū)動(dòng)名稱(chēng)是否正確");
throw new RuntimeException("加載驅(qū)動(dòng)失敗,請(qǐng)檢查是否引入Jar包或者驅(qū)動(dòng)名稱(chēng)是否正確",e);
} catch (SQLException throwables) {
System.out.println("連接數(shù)據(jù)庫(kù)失敗,請(qǐng)檢查數(shù)據(jù)庫(kù)地址,用戶名,密碼是否正確");
throw new RuntimeException("連接數(shù)據(jù)庫(kù)失敗,請(qǐng)檢查數(shù)據(jù)庫(kù)地址,用戶名,密碼是否正確",throwables);
}
return conn;
}
/**
* 關(guān)閉連接
* @param conn
*/
public static void close(Connection conn){
if(conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}注意:為什么需要使用Class.forName()來(lái)加載數(shù)據(jù)庫(kù)驅(qū)動(dòng)
是因?yàn)樵诿總€(gè)Driver中都包含有一個(gè)靜態(tài)代碼塊,實(shí)際調(diào)用的是DriverManager.registerDriver(new Driver());方法
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
public Driver() throws SQLException {
}
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
}
}
}DriverManager
該類(lèi)進(jìn)行數(shù)據(jù)庫(kù)驅(qū)動(dòng)的管理,可以注冊(cè)多個(gè)數(shù)據(jù)庫(kù)驅(qū)動(dòng),根據(jù)url來(lái)動(dòng)態(tài)的選擇不同的數(shù)據(jù)庫(kù)連接。
操作數(shù)據(jù)庫(kù)
Statement接口
使用Statement接口來(lái)操作靜態(tài)的SQL語(yǔ)句
executeUpdate方法
添加
/**
* 插入操作
* @param sql
*/
public static void doInsert(String sql){
Connection conn = getConnection();
Statement statement = null;
try {
statement = conn.createStatement();
int result = statement.executeUpdate(sql);
System.out.println(sql+"執(zhí)行成功,插入"+result+"條數(shù)據(jù)");
} catch (SQLException e) {
throw new RuntimeException("執(zhí)行失敗",e);
} finally {
if(statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
close(conn);
}
}修改
/**
* 修改操作
* @param sql
*/
public static void doUpdate(String sql){
Connection conn = getConnection();
Statement statement = null;
try {
statement = conn.createStatement();
int result = statement.executeUpdate(sql);
System.out.println(sql+"執(zhí)行成功,修改"+result+"條數(shù)據(jù)");
} catch (SQLException e) {
throw new RuntimeException("執(zhí)行失敗",e);
} finally {
if(statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
close(conn);
}
}刪除
/**
* 刪除操作
* @param sql
*/
public static void doDelete(String sql){
Connection conn = getConnection();
Statement statement = null;
try {
statement = conn.createStatement();
int result = statement.executeUpdate(sql);
System.out.println(sql+"執(zhí)行成功,刪除"+result+"條數(shù)據(jù)");
} catch (SQLException e) {
throw new RuntimeException("執(zhí)行失敗",e);
} finally {
if(statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
close(conn);
}
}PreparedStatement接口
該接口為Statement的子接口,屬于預(yù)處理操作,可以傳入帶有占位符的SQL,然后再進(jìn)行補(bǔ)充占位符,索引值從1開(kāi)始。
可以有效地禁止SQL注入
executeUpdate方法
插入
public static void doPreparedInsert(String name){
Connection conn = getConnection();
PreparedStatement statement = null;
try {
String sql = "insert into user (name) values (?)";
statement = conn.prepareStatement(sql);
statement.setString(1,name);
int result = statement.executeUpdate();
System.out.println(sql+"執(zhí)行成功,插入"+result+"條數(shù)據(jù)");
} catch (SQLException e) {
throw new RuntimeException("執(zhí)行失敗",e);
} finally {
if(statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
close(conn);
}
}在創(chuàng)建preparedStatement對(duì)象時(shí),有一個(gè)重載方法
// 第二個(gè)參數(shù)表示一個(gè)是否返回自增主鍵的一個(gè)biaoshi // Statement.RETURN_GENERATED_KEYS // Statement.NO_GENERATED_KEYS PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
在使用該P(yáng)reparedStatement執(zhí)行插入操作時(shí),可以使用statement.getGeneratedKeys()來(lái)返回一個(gè)新生成主鍵的ResultSet對(duì)象,結(jié)果集中只有一列GENERATED_KEY,存放的新生成的主鍵值
更新
與插入類(lèi)似
刪除
與插入類(lèi)似
結(jié)果集
在查詢(xún)數(shù)據(jù)時(shí),返回的是一個(gè)二維的結(jié)果集,使用ResultSet來(lái)遍歷結(jié)果集
public static void doQuery(){
String sql = "select * from user";
Connection conn = getConnection();
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
statement = conn.prepareStatement(sql);
resultSet = statement.executeQuery();
// resultSet.next 方法 將光標(biāo)向前移動(dòng)一行,最初為第一行之前,第一次調(diào)用使得第一行為當(dāng)前行
while (resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("查詢(xún)到id為"+id+",name為"+name+"的記錄");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
close(conn,statement);
}
}批量操作
public static void doBatchInsert(String sql){
Connection conn = getConnection();
PreparedStatement statement = null;
try {
statement = conn.prepareStatement(sql);
for(int i = 0;i<1000;i++){
statement.setString(1,"張三"+i);
// 積攢sql
statement.addBatch();
}
// 執(zhí)行sql
statement.executeBatch();
// 清除積攢的sql
statement.clearBatch();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
close(conn,statement);
}
}以上就是JDBC連接數(shù)據(jù)庫(kù)步驟及基本操作示例詳解的詳細(xì)內(nèi)容,更多關(guān)于JDBC連接基本操作的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- 淺談 JDBC 元數(shù)據(jù)
- Mybatis-Plus集成Sharding-JDBC與Flyway實(shí)現(xiàn)多租戶分庫(kù)分表實(shí)戰(zhàn)
- java JDBC主要組件連接數(shù)據(jù)庫(kù)及執(zhí)行SQL過(guò)程示例全面詳解
- shardingJdbc3.x?版本的分頁(yè)bug問(wèn)題解析
- 透明化Sharding-JDBC數(shù)據(jù)庫(kù)字段加解密方案
- 多數(shù)據(jù)源模式JPA整合sharding-jdbc實(shí)現(xiàn)數(shù)據(jù)脫敏
- JDBC獲取元數(shù)據(jù)demo
相關(guān)文章
詳解Java阻塞隊(duì)列(BlockingQueue)的實(shí)現(xiàn)原理
這篇文章主要介紹了詳解Java阻塞隊(duì)列(BlockingQueue)的實(shí)現(xiàn)原理,阻塞隊(duì)列是Java util.concurrent包下重要的數(shù)據(jù)結(jié)構(gòu),有興趣的可以了解一下2017-06-06
Java?在?Array?和?Set?之間進(jìn)行轉(zhuǎn)換的示例
這篇文章主要介紹了Java如何在Array和Set之間進(jìn)行轉(zhuǎn)換,在本文章中,我們對(duì)如何在?Java?中對(duì)Array和Set進(jìn)行轉(zhuǎn)換進(jìn)行一些說(shuō)明和示例,需要的朋友可以參考下2023-05-05
MybatisPlus自動(dòng)填充創(chuàng)建(更新)時(shí)間問(wèn)題
在開(kāi)發(fā)數(shù)據(jù)庫(kù)相關(guān)應(yīng)用時(shí),手動(dòng)設(shè)置創(chuàng)建和更新時(shí)間會(huì)導(dǎo)致代碼冗余,MybatisPlus提供了自動(dòng)填充功能,通過(guò)實(shí)現(xiàn)MetaObjectHandler接口并重寫(xiě)insertFill、updateFill方法,可以自動(dòng)維護(hù)創(chuàng)建時(shí)間、更新時(shí)間等字段,極大簡(jiǎn)化了代碼,這不僅提高了開(kāi)發(fā)效率,也保證了數(shù)據(jù)的可追溯性2024-09-09
詳細(xì)聊聊RabbitMQ竟無(wú)法反序列化List問(wèn)題
這篇文章主要給大家介紹了關(guān)于RabbitMQ竟無(wú)法反序列化List的相關(guān)資料,文中通過(guò)示例代碼將問(wèn)題以及解決的過(guò)程介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2021-09-09
java運(yùn)行錯(cuò)誤A JNI error的解決方案
這篇文章主要介紹了java運(yùn)行錯(cuò)誤A JNI error的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
maven多模塊項(xiàng)目依賴(lài)管理與依賴(lài)?yán)^承詳解
這篇文章主要介紹了maven多模塊項(xiàng)目依賴(lài)管理與依賴(lài)?yán)^承詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12

