簡體   English   中英

如何將SQL身份驗證添加到C#表單應用程序?

[英]How do I add SQL auth to a C# forms app?

我需要能夠針對sql server驗證用戶名和密碼,並且需要C#表單應用程序的代碼。

我設置了2個文本框(1個用戶和1個通過),然后有一個登錄按鈕。

            SqlConnection UGIcon = new SqlConnection();
        UGIcon.ConnectionString = "Data Source=HP-PC//localhost;Initial Catalog=UGI;Integrated Security=True";
        UGIcon.Open();

        string userText = textBox11.Text;
        string passText = textBox12.Text;

        SqlCommand cmd = new SqlCommand("SELECT stUsername,stPassword FROM LoginDetails WHERE stUsername='" + textBox11.Text + "' and stPassword='" + textBox12.Text + "'", UGIcon);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        if ( dt.Rows.Count > 0)
        {
            MessageBox.Show("Login Success!!");
            cmd = new SqlCommand("SELECT stRole from LoginDetails where stUsername=@stUsername", UGIcon);
            cmd.Parameters.AddWithValue("@stUsername",userText);
            string role = cmd.ExecuteScalar().ToString();
            MessageBox.Show(role);
            UGIcon.Close();
        }
        else 
        {
            MessageBox.Show("Access Denied!!");
            UGIcon.Close();
        }

我是使用“ using”語句的真正信徒。 您還可以通過在原始查詢中查詢stRole變量來保存第二查詢。 using塊將自動處理對象,因此當執行離開該區域時,將自動清理對象。

using (SqlConnection UGIcon = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=UGI;Integrated Security=True"))
        {
            UGIcon.Open();

            string userText = textBox11.Text;
            string passText = textBox12.Text;

            SqlCommand cmd = new SqlCommand("SELECT stUsername,stPassword, stRole FROM LoginDetails WHERE stUsername='" + userText + "' and stPassword='" + passText + "'", UGIcon);

            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
                if (rdr.HasRows)
                {
                    while (rdr.Read())
                    {
                        string role = rdr["stRole"].ToString();
                        MessageBox.Show(role);
                    }
                }
                else
                {
                    MessageBox.Show("Access Denied!!");
                }
            }
        }  

請檢查此代碼

SqlConnection thisConnection = new
        SqlConnection(@"Server=(local)\sqlexpress;Integrated Security=True;" +
                  "Database=northwind");
        thisConnection.Open();
        SqlCommand thisCommand = thisConnection.CreateCommand();
        thisCommand.CommandText = "Select count(*) from UserDetails
WHere UserName = "+txtUsername.text.trim().toLower() + " and Password = " +txtPassword.text.trim().toLower();
        Object countResult = thisCommand.ExecuteScalar();
        Console.WriteLine("Count of Customers = {0}", countResult);

        thisConnection.Close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM