2.5項(xiàng)目總結(jié)報告
1.任務(wù)內(nèi)容
完成登錄界面與數(shù)據(jù)庫的對接
2.任務(wù)目標(biāo)
熟悉VS的開發(fā)環(huán)境
熟悉數(shù)據(jù)庫設(shè)計方法:實(shí)體鼻弧、ER圖、數(shù)據(jù)表锦茁、數(shù)據(jù)庫表等
理解面向?qū)ο蟮幕靖拍睿侯惾列ο蟆?shí)例
能利用VS開發(fā)環(huán)境码俩,完成登錄界面與數(shù)據(jù)庫的連接訪問
3.關(guān)鍵代碼
ADO.NET查詢數(shù)據(jù)庫的流程
具體步驟:
- 導(dǎo)入命名空間;
- 定義數(shù)據(jù)庫連接字符串撑刺,創(chuàng)建Connection對象;
- 打開連接握玛;
- 利用Command對象的ExecuteReader()方法執(zhí)行Select查詢語句;
- 利用ExecuteReader()方法返回的DataReader對象讀取數(shù)據(jù)甫菠,顯示到界面上挠铲;
- 關(guān)閉連接。
捕獲.PNG
連接數(shù)據(jù)庫
SqlConnection sqlConn = new SqlConnection(connStr);
try
{
sqlConn.Open();
// 數(shù)據(jù)獲取過程
}
catch (Exception exp)
{
MessageBox.Show("數(shù)據(jù)庫連接失敗“ + exp.Message);
}
finally
{
sqlConn.Close();
}
構(gòu)造查詢語句并提交查詢
String sqlStr = "";
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登錄,而不是用戶名痰洒,用戶名可能會重復(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();
獲取數(shù)據(jù)庫返回的數(shù)據(jù)
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;
MessageBox.Show(UserInfo.userType + "登錄成功");
if (UserInfo.userType == "收銀員")
{
// 顯示收銀員主界面
MainFormUser formUser = new MainFormUser();
formUser.Show();
// 隱藏登錄界面
this.Hide();
}
if (UserInfo.userType == "庫管員")
{
// 顯示庫管員主界面
MainFormAdmin formAdmin = new MainFormAdmin();
formAdmin.Show();
// 隱藏登錄界面
this.Hide();
}
// 處理登錄
}
4.項(xiàng)目實(shí)現(xiàn)效果
收銀員登錄
2.5.gif
庫管員登錄
2.5.1.gif