JDBC常用類和介面

2021-07-10 10:20:53 字數 2538 閱讀 4423

一、註冊資料庫驅動程式

在對資料庫進行操作之前,必須要建立程式與乙個具體資料庫的連線,而在連線資料庫之前,必須要註冊該資料庫的驅動程式。完成此項工作的是drivermanager類!

註冊資料庫方驅動程式

public

static

void registerdriver(driver driver);

這是乙個靜態方法,引數driver類的物件是資料庫廠商提供的資料庫驅動程式。除此,還可以使用下面的方法:

class.forname("driver driver");

二、建立與資料庫的連線

public

static connection getconnection(string url);

public

static connection getconnection(string url, string user, string password);

該方法建立乙個與指定資料庫的連線(通過url),返回建立的連線,即connection物件。connection是乙個系統定義的介面。連線時還可以制定登入資料庫的賬號和密碼。

引數url的格式如下:

jdbc  :  子協議  :  子名稱

子協議是驅動器的名稱,子名稱是資料庫的名稱。如果是位於遠端伺服器的資料庫,還應包括主機名,埠號和資料庫例項名。

隱含情況下,connection會自動提交每一條sql語句對資料庫的修改,但如果自動提交功能被禁止,則需要呼叫connection的commit方法顯示的提交對資料庫的修改。

當乙個資料庫連線建立後,就表示開始了乙個資料庫的會話週期。當對資料庫的操作告一段落時,可通過呼叫connection的close()方法結束會話。

三、建立語句物件

1. 不帶引數的sql語句

建立語句物件的目的是為了向資料庫傳送並執行sql語句。這一步用到了connectiond物件的方法:

public statement createstatement() throws sqlexception

eg.

connection con = drivermanager.getconnection("url");  //

建立連線

statement stmt = con.createstatement();

後續**中,就可以使用stmt物件向資料庫傳送要執行的sql語句。

2.帶引數的sql語句

如果一條sql語句要執行多次,通常是使用帶引數的sql語句,可使用connection類的preparestatement()方法。

public preparedstatement preparestatement(string sql) throws sqlexception

該方法會對傳入的sql進行預編譯,然後存入preparedstatement物件。

eg.

connection con = drivermanager.getconnection(url); //

建立連線

preparedstatement ps = con.preparestatement("update emp set sal = sal + ? where eno = ?");

上面的?表示乙個引數。

preparedstatement是乙個介面,它有一下方法:

public void set***(int parameterindex, x);    //為 第幾個引數賦 x 值。set***的***是型別:int, string,date.......

excutequery();

excuteupdate();

四、向資料庫傳送sql語句

-----------------------select----------------------------

public resultset executequery(string sql) throws sqlexception

引數sql是select語句,返回乙個resultset物件,儲存查詢結果(多行多列)。

resultset是乙個藉口,它有乙個指標,指向結果集的當前行。

public boolean next()    //將resultset下移一行,返回布林型。

public *** get***("column name")   //返回當前行中某列的資料,引數可以是列名,也可以是select的序號。***是型別(int,string,date.....)

----------------------insert,update,delete------------------------

public in excuteupdate(string sql) throws sqlexception

返回乙個整型,表示本次執行實際操作的行數。

JDBC主要介面和類簡介及常用JDBC連線code

介面或者類 功能描述 driver介面 驅動器drivermanager類 驅動管理器 connection介面 資料庫連線 statement介面 執行sql語句 preparedstatement介面 執行預編譯的sql語句 callablestatement介面 執行sql的儲存過程 resu...

JDBC中常用的的類和介面

connection介面代表與特定的資料庫連線,在連線上下文中執行sql語句並返回你輸入命令的結果 1statement介面,用於已經建立連線的基礎上想資料庫傳送sql語句,在jdbc中有三種statement,preparedstatement,callablestatement,statemen...

JDBC常用介面

jdbc常用介面 statement介面 一 用於執行靜態sql語句並返回它所生成結果的物件。二 三種statement類 1.statement 由createstatement建立,用於傳送簡單的sql語句。不帶引數的 2.preparedstatement 繼承自statement介面 由pr...