1、添加一組數據;
private void btnAdd_Click(object sender, System.EventArgs e)
{
if ((txtNameAdd.Text != "") && (txtPwdAdd.Text!=""))
{
//new a dbconnection,數據庫為db目錄下的userdb.mdb
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ Server.MapPath(@".\db\userdb.mdb")
+ ";Mode=Share Deny None;Persist Security Info=False";
OleDbConnection conn = new OleDbConnection(connstr);
conn.Open ();
//檢查是否用戶名存在
string sql = "SELECT * FROM [userinfo] WHERE [user_name]='" + txtNameAdd.Text + "'" ;
OleDbCommand cmd = new OleDbCommand(sql,conn);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read() == true)
{
MsgBox("用戶名存在!");
return;
}
dr.Close ();
//使用MD5 Hash算法進行散列加密
MD5CryptoServiceProvider HashMD5 = new MD5CryptoServiceProvider();
string newPwd = ASCIIEncoding.ASCII.GetString (HashMD5.ComputeHash( ASCIIEncoding.ASCII.GetBytes(txtPwdAdd.Text )));
//將加密後的passWord添加如數據庫中
sql = "INSERT INTO [userinfo]([user_name],[user_pwd])"
+ "VALUES('" + txtNameAdd.Text + "','" + newPwd + "')";
cmd.CommandText = sql;
cmd.ExecuteNonQuery ();
conn.Close();
MsgBox("成功添加用戶:" + txtNameAdd.Text + " 密碼:" + txtPwdAdd.Text );
}
}
2、驗證數據
private void btnCheck_Click(object sender,
System.EventArgs e)
{
if ((txtNameCheck.Text != "") && (txtPwdCheck.Text!=""))
{
//new a dbconnection,數據庫為db目錄下的userdb.mdb
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ Server.MapPath(@".\db\userdb.mdb")
+ ";Mode=Share Deny None;Persist Security Info=False";
OleDbConnection conn = new OleDbConnection(connstr);
conn.Open ();
//根據用戶名,讀出密碼
string sql = "SELECT [user_pwd] FROM [userinfo] WHERE [user_name]='" + txtNameCheck.Text + "'";
OleDbCommand cmd = new OleDbCommand(sql,conn);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read() == true)
{
//將輸入密碼進行散列加密,與讀出密碼進行比較
MD5CryptoServiceProvider HashMD5 = new MD5CryptoServiceProvider();
string newPwd = ASCIIEncoding.ASCII.GetString (HashMD5.ComputeHash( ASCIIEncoding.ASCII.GetBytes(txtPwdCheck.Text )));
if (dr.GetValue(0).ToString() == newPwd)
{
MsgBox("通過驗證!");
}
else
{
MsgBox("用戶信息錯誤!");
}
}
dr.Close ();
}
}
3、彈出信息
private void MsgBox(string msg)
{
Response.Write ("<script language='JavaScript'>window.alert('" + msg + "');</script>");
}