BETA2中操作SQL數(shù)據(jù)庫
2024-07-21 02:23:48
供稿:網(wǎng)友
網(wǎng)站運營seo文章大全提供全面的站長運營經(jīng)驗及seo技術(shù)!在前面,我已經(jīng)說了如何在beta2的環(huán)境下,操作access數(shù)據(jù)庫,這次我們來看看如何通過ado。net來操作sql server數(shù)據(jù)庫!
首先我們要知道,在ado。net環(huán)境下,我們是通過system.data.sqlclient這個名字空間來操作的,另外還有一個system.data.sqltypes名字空間描述了sql server的字段類型,但它并不直接參與數(shù)據(jù)庫的操作,所以我們重點放在system.data.sqlclient的使用上!
按照慣例,我還是先列出我的例程:這個程序是我在寫一個用戶注冊系統(tǒng)時用到的,先看程序:
using system;
using system.data;
using system.data.sqlclient;
//通過用戶id號,取得用戶資料
public userinfo getuserinfo(string id)
{
sqlconnection myconn=sohotool.setconn(); //看備注一 myconn.open();
//設(shè)置sql查詢語句
string selectstr="select * from userinfo where id=" + id ;
try{
sqlcommand mycmd = new sqlcommand(selectstr,myconn);
sqldatareader mysqlreader = mycmd.executereader();
if(mysqlreader.read()) //假如存在該用戶,則錄入需要的屬性!
{
this.i_id=(int)mysqlreader["id"];
this.s_name=mysqlreader["name"].tostring();
this.s_nicheng=mysqlreader["nicheng"].tostring();
this.s_email=mysqlreader["email"].tostring();
this.s_password=mysqlreader["password"].tostring();
this.s_http=mysqlreader["http"].tostring();
this.s_oicq=mysqlreader["oicq"].tostring();
this.s_tag=mysqlreader["tag"].tostring();
this.i_charm=(int)mysqlreader["charm"];
this.i_score=(int)mysqlreader["score"];
this.i_bbswords=(int)mysqlreader["bbswords"];
this.s_pic=mysqlreader["pic"].tostring();
this.d_regtime=(datetime)mysqlreader["regtime"];
}
else
{
throw(new exception("沒有該用戶!" ));
}
}
catch(exception e)
{
throw(new exception("數(shù)據(jù)庫操作發(fā)生錯誤!" + e.message));
}
myconn.close();
return(this);
}
上面的程序?qū)崿F(xiàn)的是:通過用戶的id號來取得用戶個人資料的,下面我們看看程序中有什么新的東西!
首先我們開程序開始處引入了名字空間system.data.sqlclient;這樣我們就可以用它來操作sql數(shù)據(jù)庫了!
1. 在函數(shù)開始我們通過sqlconnection myconn=sohotool.setconn(); 得到sql數(shù)據(jù)庫的連接。
2.設(shè)置了sql查詢語句后,我們又定義了一個sqlcommand對象,并實例化,其實在ado。net中大部分sql語句都能很方便的用command來執(zhí)行,但是如果和dateset結(jié)合的話,就要引入其它的一些東西了,這個到后面我們在說!
3.定義sqldatareader對象,并通過sqlcommand對象執(zhí)行sq語句,然后 將結(jié)果存入 sqldatareader對象中,語句如下:sqldatareader mysqlreader = mycmd.executereader();
4.設(shè)置屬性,并返回需要的結(jié)果
看了我前面文章的人,應(yīng)該都能感覺到,其實操作sql數(shù)據(jù)庫原來和操作access數(shù)據(jù)庫并沒有什么區(qū)別嘛,無非是名字空間、command、reader的寫法變了個樣呀!呵呵,實際情況也幾乎就是這樣的!
備注一、上面程序中我得到sql數(shù)據(jù)庫連接是用的我自己的類,下面我吧這個程序也寫出來!
namespace soholife
{
using system;
using system.data;
using system.data.sqlclient;
public class sohotool
{
//建立與sql數(shù)據(jù)庫的連接
public static sqlconnection setconn()
{
string connstr="server=soho;database=soholife;uid=sa;pwd=;";
sqlconnection tempconn= new sqlconnection(connstr);
return(tempconn);
}
}
}
這個程序我想不需要什么解釋的吧,用處就是得到數(shù)據(jù)庫連接,有些個人體會是, beta1下,我們可以通過繼承connection,來建立自己的connection類,而在beta2下,卻無法這樣做了,不知道為什么要把connection類作成密封的形式!
好了,這次就先寫到這里,下一次,我把會說說如何通過sqlcommand對象執(zhí)行update、insert、delete語句!如果朋友們有問題也可以給我寫信討論!