Java訪問資料庫的具體步驟

2021-08-20 13:57:08 字數 2538 閱讀 6757

1.載入(註冊)資料庫

驅動載入就是把各個資料庫提供的訪問資料庫的api載入到我們程式進來,載入jdbc驅動,並將其註冊到drivermanager中,每一種資料庫提供的資料庫驅動不一樣,載入驅動時要把jar包新增到lib資料夾下,下面看一下一些主流資料庫的jdbc驅動加裁註冊的**:

//oracle8/8i/9io資料庫(thin模式)

class.forname("oracle.jdbc.driver.oracledriver").newinstance();

//sql server7.0/2000資料庫

class.forname("com.microsoft.jdbc.sqlserver.sqlserverdriver");

//sql server2005/2008資料庫

class.forname("com.microsoft.sqlserver.jdbc.sqlserverdriver");

//db2資料庫

//mysql資料庫

class.forname("com.mysql.jdbc.driver").newinstance();

2.建立鏈結

建立資料庫之間的連線是訪問資料庫的必要條件,就像南水北調調水一樣,要想調水首先由把溝通的河流打通。建立連線對於不同資料庫也是不一樣的,下面看一下一些主流資料庫建立資料庫連線,取得connection物件的不同方式:

//oracle8/8i/9i資料庫(thin模式)

string url="jdbc:oracle:thin:@localhost:1521:orcl";

string user="scott";

string password="tiger";

connection conn=drivermanager.getconnection(url,user,password);

//sql server7.0/2000/2005/2008資料庫

string url="jdbc:microsoft:sqlserver://localhost:1433;databasename=pubs";

string user="sa";

string password="";

connection conn=drivermanager.getconnection(url,user,password);

//db2資料庫

string url="jdbc:db2://localhost:5000/sample";

string user="amdin"

string password=-"";

connection conn=drivermanager.getconnection(url,user,password);

//mysql資料庫

string url="jdbc:mysql://localhost:3306/testdb?user=root&password=root&useunicode=true&characterencoding=gb2312";

connection conn=drivermanager.getconnection(url);

3. 執行sql語句

資料庫連線建立好之後,接下來就是一些準備工作和執行sql語句了,準備工作要做的就是建立statement物件preparedstatement物件,例如:

//建立statement物件

statement stmt=conn.createstatement();

//建立preparedstatement物件

string sql="select * from user where username=? and password=?";

preparedstatement pstmt=conn.preparestatement(sql);

pstmt.setstring(1,"admin");

pstmt.setstring(2,"liubin");

做好準備工作之後就可以執行sql語句了,執行sql語句:

string sql="select * from users";

resultset rs=stmt.executequery(sql);

//執行動態sql查詢

resultset rs=pstmt.executequery();

//執行insert update delete等語句,先定義sql

stmt.executeupdate(sql);

4.處理結果集

訪問結果記錄集resultset物件。例如:

while(rs.next)

5.關閉資料庫

依次將resultset、statement、preparedstatement、connection物件關 閉,釋放所占用的資源.例如:

rs.close();

stmt.clost();

pstmt.close();

con.close();

更改Mysql資料庫儲存位置的具體步驟

一.首先把mysql的服務先停掉。二.更改mysql配置檔案my.ini中的資料庫儲存主路徑 開啟mysql預設的安裝資料夾c program files mysql mysql server 5.1中的my.ini檔案,點選記事本頂部的 編輯 查詢 在查詢內容中輸入datadir後並點選 查詢下乙...

Oracle資料庫備份與還原操作具體步驟

oracle資料庫匯出操作 匯入匯出都要進行目錄建立與授權。在pl sql 裡面編寫也可以 select from dba directories 這個是檢視建立的目錄 drop directory exp dir 刪除指定名稱的目錄 查詢建立了那些子目錄 select from dba direc...

git操作的具體步驟

1.cd 路徑 進入當前目錄 2.配置git基本操作 注 沒有訊息就是好訊息 3.git init 在本地進行初始化 建立暫存區 git 檔案儲存當前專案的所有版本資訊 4.工作區 暫存區 git add 檔名 提交指定檔案 git add 提交所有檔案 git commit m 這一次提交的描述 ...