2012-03-02 46 views
0

我需要能够验证一个用户名和密码对sql服务器,我需要一个C#表单应用程序的代码。如何将SQL身份验证添加到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 [email protected]", UGIcon); 
      cmd.Parameters.AddWithValue("@stUsername",userText); 
      string role = cmd.ExecuteScalar().ToString(); 
      MessageBox.Show(role); 
      UGIcon.Close(); 
     } 
     else 
     { 
      MessageBox.Show("Access Denied!!"); 
      UGIcon.Close(); 
     } 
+0

的onclick作出的SqlConnection和一个SqlCommand和查询您的数据库,并得到一个SqlDataReader可以读取和验证用户 – f2lollpll 2012-03-02 05:35:45

+0

你尝试过什么?在SO上说“_I需要代码... ...”通常是不可接受的。我们在这里帮助你,而不是为你做你的工作。 – 2012-03-02 05:37:19

+0

只是将它添加到操作。 – 2012-03-02 05:41:31

回答

1

我是一个真正的信徒在使用 “使用” 的语句。您也可以通过在原始查询中询问stRole变量来保存第二个查询。使用块会自动处理对象,所以当执行离开这个区域时,对象会自动清理。

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

请选中该代码

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(); 
+0

我正在使用表单应用程序而不是控制台应用程序,并且我在哪里添加远程地址的IP,我只是替换(本地)? – 2012-03-02 05:50:21

+0

@John_Dong - 在这个答案中提供的代码可以很容易地适应WinForms。 – 2012-03-02 05:53:10

+0

是啊,我只是注意到你碰巧有SQL查询发送到SQL服务器添加用户和密码的任何机会? – 2012-03-02 05:56:44

相关问题