简体   繁体   English

逗号附近的语法不正确

[英]Incorrect syntax near comma

Here's an ASPX code snippet from when I was trying to get multiple values from a session. 这是我尝试从会话中获取多个值时的ASPX代码段。 I am getting an error: "Incorrect syntax near comma" (marked the line in the snippet): 我收到一个错误:“逗号附近的语法不正确”(标记在代码段中的行):

SqlCommand cmd1 = new SqlCommand("select plugin_id from profiles_plugins where profile_id=" + Convert.ToInt32(Session["cod"]), con);
        SqlDataReader dr1 = cmd1.ExecuteReader();
        var yourlist =new List<Int32>();
        if (dr1.HasRows)
        {
            while (dr1.Read())
            {
                yourlist.Add(Convert.ToInt32(dr1[0]));
            }
        }

        //String str1 = String.Join(", ", yourlist.Select(o => o.ToString()).ToArray());
            dr1.Close();
        cmd1.Dispose();
        Array k= yourlist.ToArray();
        Int32 a =Convert.ToInt32( k.GetValue(0));
        Int32 b =Convert.ToInt32( k.GetValue(1));
        Int32 c =Convert.ToInt32( k.GetValue(2));
        Int32 d =Convert.ToInt32( k.GetValue(3));
        SqlCommand cmd2 = new SqlCommand("select id,name from plugins where id =(" + a + " or " + b + " or " + c + " or " + d +  ")" , con); /// Error here?
        SqlDataReader dr2 = cmd2.ExecuteReader(); ///Error here?
        if (dr2.HasRows)
        {
            while (dr2.Read())
            {
                ListBox2.DataSource = dr2;
                ListBox2.DataBind();
            }
        }
        dr2.Close();
        cmd2.Dispose();
con.Close();

What am I missing? 我错过了什么?

SQL Query is wrong. SQL查询错误。 Change it to: 将其更改为:

    SqlCommand cmd2 = new SqlCommand("select id,name from plugins   
where id in(" + a + " , " + b + " , " + c + " , " + d +  ")" , con);

Error in this line. 这一行出错。 Try this 尝试这个

SqlCommand cmd2 = new SqlCommand("select id,name from plugins where id =" + a + "or id =" + b + " or id =" + c + " or id =" + d +  "" , con)

In your case in stead of multiple conditions OR I would suggest to use IN clause in your SQL query, and instead of . 在你的情况下,而不是多个条件或我建议在SQL查询中使用IN子句,而不是。 .. + "" + ... I would use String.Format .. + "" + ...我会使用String.Format

SqlCommand cmd2 = new SqlCommand(String.Format("select id,name from plugins where id IN ({0}, {1}, {2}, {3}", a, b, c, d,) con);

Also if you would have the same or similar error in the future you may check your query directly on SQL Server. 此外,如果您将来遇到相同或类似的错误,您可以直接在SQL Server上检查您的查询。 Just open New Query window and copy your SQL query there and then run it. 只需打开New Query窗口并在那里复制SQL查询然后运行它。 In that case it would be something like: 在这种情况下,它将是这样的:

select id,name from plugins where id IN (1, 2, 3, 4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM