數據庫中存在的用戶名跟密碼
運行結果:
代碼如下:
private void button1_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text == "")
{ MessageBox.Show("用戶名不能為空"); }
else {
if (textBox2.Text == "")
{ MessageBox.Show("密碼不能為空!"); }
else{
string name = textBox1.Text; //獲取賬號
string pastword = textBox2.Text; //獲取密碼
string conn = @" Data Source=SANM\SQLEXPRESS;Initial Catalog=data1220;Integrated Security=True;"; //連接到數據庫
SqlConnection connection = new SqlConnection(conn); //將數據庫中的數據創建一個連接 conn代表的是數據庫的一段字符
connection.Open(); //打開連接
string sql = string.Format("select count(*) from users where name='{0}' and pwd='{1}'", name, pastword);//在數據庫中查詢是否有該條記錄,根據你所想找的數據
SqlCommand command = new SqlCommand(sql, connection); //sqlcommand表示在數據庫找到想要的數據並暫時記錄起來
int i = Convert.ToInt32(command.ExecuteScalar()); //執行后返回記錄行數
if (i > 0) /*如果大於1,說明記錄存在,登錄成功 */
{
MessageBox.Show("登錄成功");
new Form2().Show(); //轉到另一個界面上
this.Hide();
}
else{ MessageBox.Show("用戶名或者密碼錯誤!"); }
connection.Close();
}
}
}
{
try
{
if (textBox1.Text == "")
{ MessageBox.Show("用戶名不能為空"); }
else {
if (textBox2.Text == "")
{ MessageBox.Show("密碼不能為空!"); }
else{
string name = textBox1.Text; //獲取賬號
string pastword = textBox2.Text; //獲取密碼
string conn = @" Data Source=SANM\SQLEXPRESS;Initial Catalog=data1220;Integrated Security=True;"; //連接到數據庫
SqlConnection connection = new SqlConnection(conn); //將數據庫中的數據創建一個連接 conn代表的是數據庫的一段字符
connection.Open(); //打開連接
string sql = string.Format("select count(*) from users where name='{0}' and pwd='{1}'", name, pastword);//在數據庫中查詢是否有該條記錄,根據你所想找的數據
SqlCommand command = new SqlCommand(sql, connection); //sqlcommand表示在數據庫找到想要的數據並暫時記錄起來
int i = Convert.ToInt32(command.ExecuteScalar()); //執行后返回記錄行數
if (i > 0) /*如果大於1,說明記錄存在,登錄成功 */
{
MessageBox.Show("登錄成功");
new Form2().Show(); //轉到另一個界面上
this.Hide();
}
else{ MessageBox.Show("用戶名或者密碼錯誤!"); }
connection.Close();
}
}
}
catch (Exception ex)/*調試報異常*/
{ MessageBox.Show("異常錯誤" + ex); }
}
{ MessageBox.Show("異常錯誤" + ex); }
}
private void button2_Click(object sender, EventArgs e) // 退出按鈕
{
Application.Exit(); // 關閉整個程序
}