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>");
}