JDBC是一組能夠執(zhí)行SQL語句的API
由于傳統(tǒng)的數(shù)據(jù)庫操作方式需要程序員掌握各個不同的數(shù)據(jù)庫的API,極其不便
因此java定義了JDBC這一標(biāo)準(zhǔn)的接口和類,為程序員操作數(shù)據(jù)庫提供了統(tǒng)一的方式
JDBC的操作方式比較單一,由五個流程組成:
1.通過數(shù)據(jù)庫廠商提供的JDBC類庫向DriverManager注冊數(shù)據(jù)庫驅(qū)動
2.使用DriverManager提供的getConnection()方法連接到數(shù)據(jù)庫
3.通過數(shù)據(jù)庫的連接對象的createStatement方法建立SQL語句對象
4.執(zhí)行SQL語句,并將結(jié)果集合返回到ResultSet中
5.使用while循環(huán)讀取結(jié)果
6.關(guān)閉數(shù)據(jù)庫資源
下面來看看具體操作Mysql數(shù)據(jù)庫的方法
準(zhǔn)備工作
首先我們需要建立一個數(shù)據(jù)庫和一張簡單的表
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)
其中這個包里面含有一份文檔,里面列舉了基本的使用方法,可以參考
我們的操作也是按照這份文檔中的內(nèi)容進(jìn)行,然后最主要的地方就是導(dǎo)入這個jar包

為了操作方便,這里使用eclipse來導(dǎo)入
右鍵項(xiàng)目-->構(gòu)件路徑-->添加外部歸檔,添加好了之后如下所示

現(xiàn)在我們正式開始使用java來操作mysql數(shù)據(jù)庫
JDBC操作實(shí)例1:最簡單的查詢操作
public class Demo {
//為了代碼緊湊性,暫時拋出所有異常
public static void main(String[] args) throws Exception {
//注冊數(shù)據(jù)庫驅(qū)動
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();
}
}
如此便可執(zhí)行show tables語句查詢出當(dāng)前數(shù)據(jù)庫含有多少張表
其中rt.getString()方法是獲取字段,這點(diǎn)需要注意
關(guān)閉資源的方式也與以往相反
不過,上面的操作方式靈活性不大,并且不嚴(yán)謹(jǐn)
實(shí)例2:優(yōu)化的查詢操作
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();
}
}
}
}

這里把異常給分別捕獲了,并且相關(guān)的字符串全部用變量定義
需要注意下循環(huán)取出數(shù)據(jù)里面的getInt()方法,此處必須知道類型和字段才能取出
如果不知道可以使用getObject(1)取出第一列,getObject(2)取出第二列,以此類推
實(shí)例3:自定義變量插入到數(shù)據(jù)庫
public class Demo {
public static void main(String[] args) {
//參數(shù)檢查
if (args.length != 3) {
System.out.println("參數(shù)形式不對");
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)行需要設(shè)置自變量,窗口中右鍵-->運(yùn)行方式-->運(yùn)行配置
然后在自變量里面寫4 susan 1993,我沒有寫中文,因?yàn)楫a(chǎn)生亂碼,目前還不清楚原因
需要注意的是,執(zhí)行插入的SQL語句比較難寫,最好是打印出SQL語句用以檢查
實(shí)例4:PreparedStatement應(yīng)用
從上面的Demo可以看到,插入數(shù)據(jù)的時候,SQL操作相當(dāng)不便
這里可以使用PreparedStatement對象來簡化SQL語句的建立
public class Demo {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("參數(shù)形式不對");
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對象的引用
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();
}
}
}
}

實(shí)例5:Batch批處理
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();
}
}
}
}

批處理比較簡單,只需先建立Statement對象,然后逐個添加批處理即可
最后使用executeBatch()方法執(zhí)行批處理
此外,PreparedStatement對象也可以使用批處理
事務(wù)處理是要求sql以單元的形式更新數(shù)據(jù)庫,要求其確保一致性
如銀行的轉(zhuǎn)賬業(yè)務(wù),一方轉(zhuǎn)出后,另一方則增加
如果出現(xiàn)異常,那么所有的操作則會回滾
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);
//取消自動提交
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è)置自動提交
conn.commit();
conn.setAutoCommit(true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
if(conn != null) {
try {
//出現(xiàn)異常則回滾操作,然后設(shè)置自動提交
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();
}
}
}
}

新聞熱點(diǎn)
疑難解答
圖片精選