2
SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Projects\\csharp\\Login1\\App_Data\\Login.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd;
SqlDataReader dr;   

protected void  LinkButton1_Click(object sender, EventArgs e)
{
 conn.Open();
 cmd=new SqlCommand("Select * from LoginTable where User Name='"+TextBox1.Text+"'",conn);
 dr=cmd.ExecuteReader();   //  <---error here

 if(dr.Read())
 {
   Label1.Text="User name already exist";
   this.Label1.ForeColor=Color.Red;
 }
 else
 {
   Label1.Text="Name available";
 }
}

它在附近显示以下错误dr=cmd.ExecuteReader();

在预期条件的上下文中指定的非布尔类型的表达式,靠近“名称”。

这里发生了什么事

4

6 回答 6

5

User Namein where 子句替换为[User Name]

于 2013-05-29T06:13:08.500 回答
3

用户名必须指定为[用户名]用户名,因此请检查一次列名

于 2013-05-29T06:14:34.197 回答
2

用户名由两个单词组成。并且还使用参数化查询。

cmd=new SqlCommand("Select * from LoginTable where [User Name]=@userName",conn);
cmd.Parameters.AddWithValue("@userName", TextBox1.Text);
于 2013-05-29T06:14:36.013 回答
2

您不应UserName在此语句之间留出空格:

cmd=new SqlCommand("Select * from LoginTable where **User Name** = '"+TextBox1.Text+"'", conn);
于 2013-05-29T06:15:28.750 回答
2

The user name must be specified as [User Name] or UserName so please check column name once

and also check for reserved keywords if you use them as column names please kept in square brasses [ ]

cmd=new SqlCommand("Select * from LoginTable where [User Name] = @userName",conn);
cmd.Parameters.AddWithValue("@userName", TextBox1.Text);

OR

cmd=new SqlCommand("Select * from LoginTable where UserName = @userName",conn);
cmd.Parameters.AddWithValue("@userName", TextBox1.Text);
于 2013-05-29T08:50:35.723 回答
2

除了字段名称(用户名?)中可能存在的拼写错误外,这不是应该这样做的。尝试这个:

cmd = new SqlCommand("IF EXISTS(SELECT 1 FROM LoginTable where [User Name]=@p)" +
"SELECT 1 ELSE SELECT 0", conn);
cmd.Parameters.AddWithValue("@p", TextBox1.Text);

if(Convert.ToBoolean(cmd.ExecuteScalar()))
{
   Label1.Text="User name already exist";
   this.Label1.ForeColor=Color.Red;
}
else
   Label1.Text="Name available";
于 2013-05-29T06:29:30.457 回答