2016-04-23 40 views
0

我做了一个SQL Server表的注册页面,现在我想做一个注册页面。如何检查输入的值是否存在?C#&SQL Server:如何做登录检查

这里是我的代码块:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.SqlClient; 

public partial class index : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 

    protected void btnSignIN_Click(object sender, EventArgs e) 
    { 
     string str = "Data Source=(LocalDB)\\MSSQLLocalDB;"; 
     str += "AttachDbFilename=|DataDirectory|Database.mdf;"; 
     str += "Integrated Security= True"; 
     string userName = txtUserNameLogIN.Text; 
     string password = txtPasswordLogIN.Text; 
     SqlConnection c = new SqlConnection(str); 
     SqlCommand cmd = new SqlCommand("SELECT UserName FROM [Table] WHERE [email protected]", c); 
     cmd.Parameters.AddWithValue("@userName", userName); 

    } 
} 

在这里,我不`吨知道该怎么办......

任何帮助将不胜感激。

回答

0

如果你想检查用户名已经存在,你可以使用简单的检查EXISTS - 类似如下:

var cmd = new SqlCommand("SELECT COUNT(1) FROM [Table] WHERE UserName = @userName", c); 
cmd.Parameters.AddWithValue("@userName", userName); 
var existingCount = Convert.ToInt32(cmd.ExecuteScalar()); 
if (existingCount > 0) 
{ 
    // exists logic 
} 

编辑:

侧面说明,但很重要的 - 你是处理一次性物品,并考虑处置它们:

string str = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True"; 
    string userName = txtUserNameLogIN.Text; 
    string password = txtPasswordLogIN.Text; 
    SqlConnection c = null; 
    try 
    { 
     using (c = new SqlConnection(str)) 
     { 
      using (var cmd = new SqlCommand("SELECT COUNT(1) FROM [Table] WHERE UserName = @userName", c)) 
      { 
       cmd.Parameters.AddWithValue("@userName", userName); 
       var existingCount = Convert.ToInt32(cmd.ExecuteScalar()); 
       if (existingCount > 0) 
       { 
        // exists logic 
       } 
      } 
     } 
    } 
    catch(Exception exc) 
    { 
     // exception handling code comes here 
    } 
    finally 
    { 
     // ensure that connection is properly closed, if database operation is done 
     if (c != null && c.State == ConnectionState.Open) 
      c.Close(); 
    } 
+0

谢谢!它为我工作 – D4NieLDev

0
protected void btnSignIN_Click(object sender, EventArgs e) 
{ 
    string str = "Data Source=(LocalDB)\\MSSQLLocalDB;"; 
    str += "AttachDbFilename=|DataDirectory|Database.mdf;"; 
    str += "Integrated Security= True"; 
    string userName = txtUserNameLogIN.Text; 
    string password = txtPasswordLogIN.Text; 
    SqlConnection c = new SqlConnection(str); 
    SqlCommand cmd = new SqlCommand("SELECT UserName FROM [Table] WHERE [email protected]", c); 

    SqlDataReader reader = cmd.ExecuteReader(); 
if (reader.Read()) 
      MessageBox.Show("connected"); 
     else 
      MessageBox.Show("failed to connect"); 

     c.Close(); 

}