Statement執(zhí)行DML語句以及數(shù)據(jù)庫鏈接封裝

一.數(shù)據(jù)庫封裝。

根據(jù)前面執(zhí)行DQL和DDL語句,我們發(fā)現(xiàn),在執(zhí)行數(shù)據(jù)庫操作中,數(shù)據(jù)庫的鏈接以及關(guān)閉方法是相同的,那么,是不是可以將這兩部分代碼單獨提取出來,需要鏈接時只需要調(diào)用就可以呢?


數(shù)據(jù)庫鏈接封裝


數(shù)據(jù)庫鏈接封裝

1.驅(qū)動加載

staticStringurl="jdbc:mysql://localhost:3306/test";

staticStringname="root";

staticStringpassword="root";

//靜態(tài)代碼塊只加載一次

static{

try{

Class.forName("com.mysql.jdbc.Driver");

}?? catch(? Exception e? )? {

e.printStackTrace? (?? )?? ;

throw newRuntimeException(?? e? )?? ;??? }??? }

2.數(shù)據(jù)庫鏈接

public??? staticConnection??? getConnection(?? )??? {

Connection?? connection?? =?? null??? ;

try{

??????? connection=DriverManager.getConnection(url,name,password);

}?? catch?? (?? Exception e?? ) ?? {

e.printStackTrace(?? )?? ;? }

returnconnection;?? }

3.鏈接關(guān)閉

public static voidclose(Connection connection,Statement statement){

if(connection!=null){

try{

connection.close();

}catch(Exception e) {

e.printStackTrace();??? }

System.out.println("關(guān)閉成功");?? }

if(statement!=null){

try{

statement.close();

}catch(Exception e) {

e.printStackTrace(? ) ;?? }?? }? }

二.執(zhí)行DML語句


核心代碼


運行結(jié)果


1.調(diào)用jdbcUtil鏈接數(shù)據(jù)庫

public static voidmain(String [] args){

Connection connection=null;

Statement statement=null;

try{

//調(diào)用jdbcUtil鏈接數(shù)據(jù)庫

connection=jdbcUtil.getConnection();

//創(chuàng)建statement對象

statement=connection.createStatement();

}catch(Exception? e)?? {

e.printStackTrace();

throw newRuntimeException(e)? ;? }?? finally{

//關(guān)閉鏈接

jdbcUtil.close(connection,statement)??? ;?? }??? }

2.ResultSet接口:用于封裝查詢出啦的數(shù)據(jù)

boolean next ()將光標(biāo)移動到下一行

getXX()獲取列的值

3.取值的三種方式

1).索引取值

int id=resultSet.getInt(1);

String name=resultSet.getString(2);

System.out.println("id:"+id+"姓名:"+name);

2.)名稱取值

intid=resultSet.getInt("id");

String name=resultSet.getString("name");

System.out.println("id:"+id+"姓名:"+name);

3)遍歷取值

while (resultSet.next()){

int id=resultSet.getInt("id");

String name=resultSet.getString("name");

System.out.println("id:"+id+"姓名:"+name);??? }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,765評論 18 399
  • JDBC簡介 SUN公司為了簡化、統(tǒng)一對數(shù)據(jù)庫的操作,定義了一套Java操作數(shù)據(jù)庫的規(guī)范,稱之為JDBC。JDBC...
    奮斗的老王閱讀 1,541評論 0 51
  • 本人的環(huán)境為Myeclipse10、MySQL5.7.15 本文包括:簡介JDBC編程步驟打通數(shù)據(jù)庫程序詳解—Dr...
    廖少少閱讀 3,998評論 7 39
  • 一. Java基礎(chǔ)部分.................................................
    wy_sure閱讀 3,835評論 0 11
  • 畫了點背景感覺好看多了
    一臨江仙閱讀 187評論 8 12