System.Data.SqlClient.SqlException:','附近的语法不正确。错误

时间:2018-02-23 09:04:17

标签: c# asp.net sql-server

这是我得到的错误:

System.Data.SqlClient.SqlException: Incorrect syntax near ','. error

这是我的代码:

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

namespace LOGIN_PAGE
{
    public partial class login : System.Web.UI.Page
    {


        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ToString());
            string s = "select count(*) from signup where [username]='" + txtusername.Text + "' ,  [passwd]= '" + txtpasswd.Text + "'";
            SqlCommand cmd = new SqlCommand(s, con);
            con.Open();
            int i = Convert.ToInt32(cmd.ExecuteScalar());
            if(i>0)
            {
                Response.Redirect("analysis.aspx");
            }
           else
            {
                lblDisplay.Text=("Invalid User Credentials..");
            }
            con.Close();
        }
    }
}

有人能指出我正确的方向,找出导致此错误的原因以及解决方法吗?

2 个答案:

答案 0 :(得分:1)

更新您的查询,如下所示:

string myQuery = "select count(*) from signup where [username]=@userName and  [passwd]= @password";

string connectionString='';//your connection string
using (SqlConnection conn = new SqlConnection(connectionString))
{
    using (SqlCommand cmd = new SqlCommand(myQuery , conn))
    {        
        connection.Open();
        cmd.Parameters.Add(new SqlParameter("userName", txtusername.Text));
        cmd.Parameters.Add(new SqlParameter("password", txtpasswd.Text));
        cmd.ExecuteNonQuery();
    }
}

内联查询执行不适合使用,因为它会导致SQL注入,更好地使用如下:

<input type="date" name="dob" required="required" min="2000-02-23"/>

答案 1 :(得分:0)

这是错误。你应该在2之间使用AND where子句。使用如下。更改以粗体标记。

string s =“select count(*)来自注册,其中[username] ='”+ txtusername.Text +“' AND [passwd] ='”+ txtpasswd.Text +“'” ;

也不要使用内联查询,因为它们可能会导致SQL注入。始终使用存储过程。了解有关sqlinjection的更多信息。