C#實現連接sql2008數據庫,使用數據庫中的用戶名密碼實現登入


            數據庫中存在的用戶名跟密碼

 

 運行結果:

 

代碼如下:

     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();
                    }
                }
            }
            catch (Exception ex)/*調試報異常*/
            { MessageBox.Show("異常錯誤" + ex); }
        }

 private void button2_Click(object sender, EventArgs e)      //  退出按鈕
        {
            Application.Exit();   // 關閉整個程序
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM