有個存儲過程
alter procedure pr_getsinglestudent
(
@studentname varchar(50)
)
as
select
studentid
from
student
where
studentname = @studentname
執行之后查詢是否有相同的用戶名,有的話提示用戶名該用戶名已注冊,沒有的話正常注冊
代碼如下
studentctr student = new studentctr();
sqldatareader dr=student.getsinglestudent(textbox_studentname.text.trim());
if(int32.referenceequals(dr,null))
{
student.addstudent(textbox_studentname.text.trim(),textbox_password.text.trim(),int32.parse(session["teacherid"].tostring()));
每次輸入都說該用戶名已注冊,不論輸入的是數據庫中有的還是沒有的
其實這個錯誤犯的是習慣性,應為一般比如象datagrid和listbox數據綁定的時候,就直接指定數據源,然后databind()就可以了,以為sqldatareader 是連接數據庫以后,讀取了數據的,所以就拿來直接比較,后來經過查找資料及向別人請教,得知了sqldatareader只是提供了一個數據的只讀的指向,所以一般的一些label或者textbox的text的屬性賦值的時候,都要先 sqldatareader read()后,再賦值。
上面程序最后更改為
if (dr.read())
{
//已注冊
}
還有就是在 visual c# .net 中 datareader 沒有 recordcount 屬性,就是沒有提供給我們統計記錄總數,要靠我們自己來實現,下面是微軟的例子
string myconnstring =
"user id=sa;password=sa;initial catalog=pubs;data source=mysqlserver";
string myselectquery = "select * from authors";
sqlconnection myconnection = new sqlconnection(myconnstring);
sqlcommand mycommand = new sqlcommand(myselectquery, myconnection);
myconnection.open();
sqldatareader myreader ;
myreader = mycommand.executereader();
int recordcount = 0;
try
{
while (myreader.read())
{
recordcount++;
}
if (recordcount == 0)
messagebox.show("no data returned");
else
messagebox.show("number of records returned:" + recordcount);
}
catch (exception ex)
{
messagebox.show(ex.tostring());
}
finally
{
myreader.close();
myconnection.close();
}
這個例子可以簡化,沒有錯誤捕獲和提示,代碼如下
string myconnstring =
"user id=sa;password=sa;initial catalog=pubs;data source=mysqlserver";
string myselectquery = "select * from authors";
sqlconnection myconnection = new sqlconnection(myconnstring);
sqlcommand mycommand = new sqlcommand(myselectquery, myconnection);
myconnection.open();
sqldatareader myreader ;
myreader = mycommand.executereader();
int recordcount = 0;
if(myreader.read() )
{recordcount ++;}
如果要是賦值給一個label的話,可以在上面加一句,label1.text=recordcount ;
新聞熱點
疑難解答