JDBC數(shù)據(jù)庫的使用操作總結(jié)
JDBC是一組能夠執(zhí)行SQL語句的API
由于傳統(tǒng)的數(shù)據(jù)庫操作方式需要程序員掌握各個(gè)不同的數(shù)據(jù)庫的API,極其不便
因此java定義了JDBC這一標(biāo)準(zhǔn)的接口和類,為程序員操作數(shù)據(jù)庫提供了統(tǒng)一的方式
JDBC的操作方式比較單一,由五個(gè)流程組成:
1.通過數(shù)據(jù)庫廠商提供的JDBC類庫向DriverManager注冊(cè)數(shù)據(jù)庫驅(qū)動(dòng)
2.使用DriverManager提供的getConnection()方法連接到數(shù)據(jù)庫
3.通過數(shù)據(jù)庫的連接對(duì)象的createStatement方法建立SQL語句對(duì)象
4.執(zhí)行SQL語句,并將結(jié)果集合返回到ResultSet中
5.使用while循環(huán)讀取結(jié)果
6.關(guān)閉數(shù)據(jù)庫資源
下面來看看具體操作Mysql數(shù)據(jù)庫的方法
準(zhǔn)備工作
首先我們需要建立一個(gè)數(shù)據(jù)庫和一張簡單的表
mysql> create database person;
Query OK, 1 row affected (0.00 sec)
mysql> use person;
Database changed
mysql> create table student(
-> id int,
-> name varchar(20),
-> birth year
-> ) default charset=utf8;
Query OK, 0 rows affected (0.10 sec)
然后往里面插入幾條數(shù)據(jù)
mysql> insert into student values
-> (1,'張三',1990),
-> (2,'李四',1991),
-> (3,'王五',1992);
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
這樣一張簡單的表就建好了
mysql> select * from student;
+------+--------+-------+
| id | name | birth |
+------+--------+-------+
| 1 | 張三 | 1990 |
| 2 | 李四 | 1991 |
| 3 | 王五 | 1992 |
+------+--------+-------+
rows in set (0.00 sec)
接下來,去mysql官網(wǎng)下載數(shù)據(jù)庫連接器這個(gè)包
其中這個(gè)包里面含有一份文檔,里面列舉了基本的使用方法,可以參考
我們的操作也是按照這份文檔中的內(nèi)容進(jìn)行,然后最主要的地方就是導(dǎo)入這個(gè)jar包
為了操作方便,這里使用eclipse來導(dǎo)入
右鍵項(xiàng)目-->構(gòu)件路徑-->添加外部歸檔,添加好了之后如下所示
現(xiàn)在我們正式開始使用java來操作mysql數(shù)據(jù)庫
JDBC操作實(shí)例1:最簡單的查詢操作
import java.sql.*;
public class Demo {
//為了代碼緊湊性,暫時(shí)拋出所有異常
public static void main(String[] args) throws Exception {
//注冊(cè)數(shù)據(jù)庫驅(qū)動(dòng)
Class.forName("com.mysql.jdbc.Driver");
//建立數(shù)據(jù)庫連接
//參數(shù)一:jdbc:mysql//地址:端口/數(shù)據(jù)庫,參數(shù)二:用戶名,參數(shù)三:密碼
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/person","root","admin");
//創(chuàng)建SQL語句
Statement st = conn.createStatement();
//執(zhí)行語句,返回結(jié)果
ResultSet rt = st.executeQuery("show tables");
//循環(huán)取出結(jié)果
while(rt.next()) {
//獲取字段
System.out.println(rt.getString("Tables_in_person"));
}
//關(guān)閉資源,最先打開的最后關(guān)
rt.close();
st.close();
conn.close();
}
}
運(yùn)行結(jié)果:student
如此便可執(zhí)行show tables語句查詢出當(dāng)前數(shù)據(jù)庫含有多少張表
其中rt.getString()方法是獲取字段,這點(diǎn)需要注意
關(guān)閉資源的方式也與以往相反
不過,上面的操作方式靈活性不大,并且不嚴(yán)謹(jǐn)
實(shí)例2:優(yōu)化的查詢操作
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/person";
String user = "root";
String pwd = "admin";
String sql = "select * from student";
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,user,pwd);
st = conn.createStatement();
//執(zhí)行查詢語句,另外也可以用execute(),代表執(zhí)行任何SQL語句
rs = st.executeQuery(sql);
while(rs.next()) {
System.out.println(rs.getObject(1) + " " +
rs.getObject(2) + " " + rs.getInt("birth"));
}
//分別捕獲異常
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
//判斷資源是否存在
if(rs != null) {
rs.close();
//顯示的設(shè)置為空,提示gc回收
rs = null;
}
if(st != null) {
st.close();
st = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
運(yùn)行結(jié)果:
這里把異常給分別捕獲了,并且相關(guān)的字符串全部用變量定義
需要注意下循環(huán)取出數(shù)據(jù)里面的getInt()方法,此處必須知道類型和字段才能取出
如果不知道可以使用getObject(1)取出第一列,getObject(2)取出第二列,以此類推
實(shí)例3:自定義變量插入到數(shù)據(jù)庫
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo {
public static void main(String[] args) {
//參數(shù)檢查
if (args.length != 3) {
System.out.println("參數(shù)形式不對(duì)");
System.exit(0);
}
String id = args[0];
String name = args[1];
String birth = args[2];
String sql = "insert into student values(" + id + ",'" + name +
"'," + "'" + birth + "')";
System.out.println(sql);
String url = "jdbc:mysql://localhost:3306/person";
String user = "root";
String pwd = "admin";
Connection conn = null;
Statement st = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,user,pwd);
st = conn.createStatement();
//注意,此處是excuteUpdate()方法執(zhí)行
st.executeUpdate(sql);
//分別捕獲異常
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(st != null) {
st.close();
st = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
運(yùn)行結(jié)果:
這里運(yùn)行需要設(shè)置自變量,窗口中右鍵-->運(yùn)行方式-->運(yùn)行配置
然后在自變量里面寫4 susan 1993,我沒有寫中文,因?yàn)楫a(chǎn)生亂碼,目前還不清楚原因
需要注意的是,執(zhí)行插入的SQL語句比較難寫,最好是打印出SQL語句用以檢查
實(shí)例4:PreparedStatement應(yīng)用
從上面的Demo可以看到,插入數(shù)據(jù)的時(shí)候,SQL操作相當(dāng)不便
這里可以使用PreparedStatement對(duì)象來簡化SQL語句的建立
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Demo {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("參數(shù)形式不對(duì)");
System.exit(0);
}
String id = args[0];
String name = args[1];
String birth = args[2];
String url = "jdbc:mysql://localhost:3306/person";
String user = "root";
String pwd = "admin";
Connection conn = null;
//聲明PreparedStatement對(duì)象的引用
PreparedStatement pst = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,user,pwd);
//使用?代替變量
pst = conn.prepareStatement("insert into student values (?,?,?)");
//給指定參數(shù)的位置設(shè)定變量
pst.setString(1, id);
pst.setString(2, name);
pst.setString(3, birth);
pst.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(pst != null) {
pst.close();
pst = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
運(yùn)行結(jié)果:
實(shí)例5:Batch批處理
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/person";
String user = "root";
String pwd = "admin";
Connection conn = null;
Statement st = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,user,pwd);
st = conn.createStatement();
//添加批處理
st.addBatch("insert into student values(6,'Jerry','1995')");
st.addBatch("insert into student values(7,'Greg','1996')");
st.addBatch("insert into student values(8,'Ryan','1997')");
//執(zhí)行批處理
st.executeBatch();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(st != null) {
st.close();
st = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
運(yùn)行結(jié)果:
批處理比較簡單,只需先建立Statement對(duì)象,然后逐個(gè)添加批處理即可
最后使用executeBatch()方法執(zhí)行批處理
此外,PreparedStatement對(duì)象也可以使用批處理
PreparedStatement ps = conn.prepareStatement("insert into student values(?,?,?)");
ps.setInt(1,8);
ps.setString(2,"GG");
ps.setString(3,"1996");
ps.addBatch();
ps.executeBatch();
實(shí)例6:Transaction事務(wù)處理
事務(wù)處理是要求sql以單元的形式更新數(shù)據(jù)庫,要求其確保一致性
如銀行的轉(zhuǎn)賬業(yè)務(wù),一方轉(zhuǎn)出后,另一方則增加
如果出現(xiàn)異常,那么所有的操作則會(huì)回滾
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/person";
String user = "root";
String pwd = "admin";
Connection conn = null;
Statement st = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,user,pwd);
//取消自動(dòng)提交
conn.setAutoCommit(false);
st = conn.createStatement();
st.addBatch("insert into student values(6,'Jerry','1995')");
st.addBatch("insert into student values(7,'Greg','1996')");
st.addBatch("insert into student values(8,'Ryan','1997')");
st.executeBatch();
//提交后設(shè)置自動(dòng)提交
conn.commit();
conn.setAutoCommit(true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
if(conn != null) {
try {
//出現(xiàn)異常則回滾操作,然后設(shè)置自動(dòng)提交
conn.rollback();
conn.setAutoCommit(true);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
} finally {
try {
if(st != null) {
st.close();
st = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
運(yùn)行結(jié)果:
- JDBC用法小結(jié)
- Java 數(shù)據(jù)庫連接(JDBC)的相關(guān)總結(jié)
- Java JDBC連接數(shù)據(jù)庫常見操作總結(jié)
- 使用JDBC連接Mysql數(shù)據(jù)庫會(huì)出現(xiàn)的問題總結(jié)
- JDBC連接mysql亂碼異常問題處理總結(jié)
- JDBC常用接口總結(jié)
- javaweb學(xué)習(xí)總結(jié)——使用JDBC處理MySQL大數(shù)據(jù)
- Java中JDBC事務(wù)與JTA分布式事務(wù)總結(jié)與區(qū)別
- java開發(fā)中基于JDBC連接數(shù)據(jù)庫實(shí)例總結(jié)
- JDBC連接Sql Server 2005總結(jié)
- 淺析JAVA常用JDBC連接數(shù)據(jù)庫的方法總結(jié)
- JDBC的擴(kuò)展知識(shí)點(diǎn)總結(jié)
相關(guān)文章
SQL Server 出現(xiàn)Error: 1326錯(cuò)誤(管理器無法連接遠(yuǎn)程數(shù)據(jù)庫)問題解決方案
這篇文章主要介紹了SQL Server 出現(xiàn)Error: 1326錯(cuò)誤(管理器無法連接遠(yuǎn)程數(shù)據(jù)庫)問題解決方案的相關(guān)資料,這里對(duì)1326 錯(cuò)誤進(jìn)行了詳細(xì)介紹及解決辦法,需要的朋友可以參考下2016-11-11MySQL索引失效十種場(chǎng)景與優(yōu)化方案
這篇文章主要介紹了MySQL索引失效十種場(chǎng)景與優(yōu)化方案,文中有詳細(xì)的代碼示例供參考閱讀,感興趣的朋友可以看一下2023-05-05rpm -ivh方式安裝mysql并修改數(shù)據(jù)存儲(chǔ)位置的實(shí)現(xiàn)
在Linux環(huán)境下進(jìn)行MySQL的安裝可以使用不同的方式,但在本文中我們將關(guān)注一種特定的方式,即通過RPM包的方式進(jìn)行安裝,本文主要介紹了rpm -ivh方式安裝mysql并修改數(shù)據(jù)存儲(chǔ)位置的實(shí)現(xiàn),感興趣的可以了解一下2023-09-09mysql事件之修改事件(ALTER EVENT)、禁用事件(DISABLE)、啟用事件(ENABLE)、事件重命名及數(shù)
這篇文章主要介紹了mysql事件之修改事件(ALTER EVENT)、禁用事件(DISABLE)、啟用事件(ENABLE)、事件重命名及數(shù)據(jù)庫事件遷移操作,詳細(xì)分析了mysql數(shù)據(jù)庫事件的修改、禁用、啟用、重命名、遷移等原理與操作技巧,需要的朋友可以參考下2019-12-12MySQL按時(shí)間統(tǒng)計(jì)數(shù)據(jù)的方法總結(jié)
在本篇MYSQL的內(nèi)容里,我們給大家整理了關(guān)于按時(shí)間統(tǒng)計(jì)數(shù)據(jù)的方法內(nèi)容,有需要的朋友們學(xué)習(xí)下。2019-02-02Mysql實(shí)現(xiàn)全文檢索、關(guān)鍵詞跑分的方法實(shí)例
這篇文章主要給大家介紹了關(guān)于Mysql實(shí)現(xiàn)全文檢索、關(guān)鍵詞跑分的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09