畫面主要動能:
1缨睡、對數(shù)據(jù)庫的數(shù)據(jù)進行連接,并讀取數(shù)據(jù)內(nèi)容徘铝;
2耳胎、實現(xiàn)登錄信息到數(shù)據(jù)庫服務器上進行驗證并登錄成功;
一惕它、后臺數(shù)據(jù)庫表結(jié)構(gòu)
數(shù)據(jù)庫1.PNG
三怕午、ADO.NET查詢數(shù)據(jù)庫的流程
查詢數(shù)據(jù)庫的流程.PNG
具體步驟:
導入命名空間;
運用Connection對象建立與數(shù)據(jù)庫連接;
打開連接淹魄;
利用Command對象的ExecuteReader()方法執(zhí)行Select查詢語句郁惜;
利用ExecuteReader()方法返回的DataReader對象讀取數(shù)據(jù),顯示到界面上甲锡;
關閉連接兆蕉。
四羽戒、重要代碼
1、與數(shù)據(jù)庫構(gòu)建連接
String connStr = "Data Source=.;Initial Catalog=SuperMarketSales;Integrated Security=True";
SqlConnection sqlConn = new SqlConnection(connStr);
try
{
// 連接數(shù)據(jù)庫
sqlConn.Open();
// 注意USER是SQL Server關鍵字虎韵,表名不能命名為USER半醉,而應當用USERS
String sqlStr = "select * from EMPLOYEE where ID=@id and PASSWORD=@pwd";
SqlCommand cmd = new SqlCommand(sqlStr, sqlConn);
// 注意是用用戶ID登錄,而不是用戶名劝术,用戶名可能會重復
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ù)庫中查詢到記錄缩多,則表示可以登錄
catch (Exception exp)
{
MessageBox.Show("數(shù)據(jù)庫連接失敗");
return;
}
finally
{
sqlConn.Close();
}
2、用戶驗證登錄
if (dr.HasRows)
{
dr.Read();
UserInfo.userId = int.Parse(dr["ID"].ToString());
UserInfo.userName = dr["NAME"].ToString();
UserInfo.userPwd = dr["PASSWORD"].ToString();
UserInfo.userType = dr["TYPE"].ToString();
UserInfo.userPhone = dr["PHONE"].ToString();
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();
}
}
else
{
MessageBox.Show("用戶名或密碼錯誤", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}