一谓传、GIF圖
1.gif
二续挟、主要功能及數(shù)據(jù)庫(kù)表結(jié)構(gòu)
主要功能:
2.6是為了實(shí)現(xiàn)數(shù)據(jù)庫(kù)和登錄界面的一個(gè)對(duì)接侥衬,通過(guò)上圖可以看出浇冰,我們從登陸界面登錄即可進(jìn)入收銀員/管理員主界面。
數(shù)據(jù)庫(kù)表結(jié)構(gòu):
2.PNG
3.PNG
四际乘、ADO.NTE數(shù)據(jù)庫(kù)的流程
4.PNG
具體步驟:
1.導(dǎo)入命名空間;
2.運(yùn)用Connection對(duì)象建立與數(shù)據(jù)庫(kù)連接;
3.打開連接投蝉;
4.利用Command對(duì)象的ExecuteReader()方法執(zhí)行Select查詢語(yǔ)句;
5.利用ExecuteReader()方法返回的DataReader對(duì)象讀取數(shù)據(jù)关拒,顯示到界面上庸娱;
6.關(guān)閉連接。
五归露、重要代碼片段及詳細(xì)描述
1.編程訪問(wèn)數(shù)據(jù)庫(kù)
(1).連接數(shù)據(jù)庫(kù)
SqlConnection sqlConn = new SqlConnection(connStr);
try
{
// 連接數(shù)據(jù)庫(kù)
sqlConn.Open();
}
catch (Exception exp)
{
MessageBox.Show(“訪問(wèn)數(shù)據(jù)庫(kù)出錯(cuò)");
}
finally
{
sqlConn.Close();
}
(2).構(gòu)造查詢語(yǔ)句并提交查詢
String sqlStr = "select * from USERS";
SqlCommand cmd = new SqlCommand(sqlStr, sqlConn);
SqlDataReader dr = cmd.ExecuteReader();
(3).獲取數(shù)據(jù)庫(kù)返回的數(shù)據(jù)
// 解析數(shù)據(jù)
while (dr.Read())
{
String Id = dr["ID"].ToString();
String Name = dr["NAME"].ToString();
String Password = dr["PASSWORD"].ToString();
String Phone = dr["PHONE"].ToString();
2.登錄界面連接數(shù)據(jù)庫(kù)
(1).連接數(shù)據(jù)庫(kù)
SqlConnection sqlConn = new SqlConnection(connStr);
try
{
sqlConn.Open();
}
catch (Exception exp)
{
MessageBox.Show("數(shù)據(jù)庫(kù)連接失敗");
}
finally
{
sqlConn.Close();
}
(2).構(gòu)造查詢語(yǔ)句并提交查詢
if (this.cbb_UserType.Text == "收銀員")
{
// 注意USER是SQL Server關(guān)鍵字剧包,表名不能命名為USER疆液,而應(yīng)當(dāng)用USERS
sqlStr = "select * from USERS where ID=@id and PASSWORD=@pwd";
}
else
{
sqlStr = "select * from ADMIN where ID=@id and PASSWORD=@pwd";
}
SqlCommand cmd = new SqlCommand(sqlStr, sqlConn);
// 注意是用用戶ID登錄,而不是用戶名馅闽,用戶名可能會(huì)重復(fù)
cmd.Parameters.Add(new SqlParameter("@id", this.tb_User.Text.Trim()));
cmd.Parameters.Add(new SqlParameter("@pwd", this.tb_Password.Text.Trim()));
SqlDataReader dr = cmd.ExecuteReader();
(3).獲取數(shù)據(jù)庫(kù)返回的數(shù)據(jù)
// 如果從數(shù)據(jù)庫(kù)中查詢到記錄馍迄,則表示可以登錄
if (dr.HasRows)
{
dr.Read();
UserInfo.userId = int.Parse(dr["ID"].ToString());
UserInfo.userName = dr["NAME"].ToString();
UserInfo.userPwd = dr["PASSWORD"].ToString();
UserInfo.userPhone = dr["PHONE"].ToString();
UserInfo.userType = this.cbb_UserType.Text;
}
if (UserInfo.userType == "收銀員")
{
// 顯示收銀員主界面
MainFormUser formUser = new MainFormUser();
formUser.Show();
}
if (UserInfo.userType == "庫(kù)管員")
{
// 顯示庫(kù)管員主界面
MainFormAdmin formAdmin = new MainFormAdmin();
formAdmin.Show();
}