“'附近的语法不正确

时间:2014-01-15 12:26:59

标签: c# asp.net sql

这是有错误的代码背后的页面

if (Session["username"] != null)
   {


        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["registerCS"].ConnectionString;

       string sql1 = "Select pemgrp from Profile where userID = '" + Session["username"].ToString() + "'";
      string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";

        SqlCommand cmd = new SqlCommand();
        SqlDataReader dr;

        DataTable dt = new DataTable();

        cmd.CommandText = sql;
        cmd.Connection = con;

        //open connection and execute command
        con.Open();
        dr = cmd.ExecuteReader();

        if (dr.Read())
        {
        lb_classmates.Text = dr[0].ToString();

        }
    }

然而,当我跑步时,它给了我这个错误: 关键字'where'附近的语法不正确。

  

描述:执行期间发生了未处理的异常   当前的网络请求。请查看堆栈跟踪了解更多信息   有关错误的信息以及它在代码中的起源。

     

异常详细信息:System.Data.SqlClient.SqlException:不正确   关键字'where'附近的语法。

4 个答案:

答案 0 :(得分:8)

因为您正在使用子查询,所以

string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";

应该是

string sql = "Select studname from Profile where pemgrp in (" + sql1+ ")";

您应该使用Parametereized queries来避免SQL injection

答案 1 :(得分:2)

我认为应该是

string sql = "Select studname from Profile where pemgrp in (" + sql1+ ")";

而不是

string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";

我强烈建议您使用参数化查询

答案 2 :(得分:0)

你应该使用像这样的参数化查询

string sql = "Select studname from Profile where pemgrp = @p1";

并传递参数

command.Parameters.AddWithValue("@p1",sql1);

答案 3 :(得分:0)

No One's answer当然是对的。

如果要在查询中使用子查询,则应使用IN (Transact-SQL)

  

确定指定的值是否与子查询中的任何值匹配   或列表。

test_expression [ NOT ] IN 
( subquery | expression [ ,...n ]
) 

此外,您应始终使用parameterized queries。这种字符串连接对SQL Injection攻击是开放的。

另请考虑使用using处理您的SqlConnection

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["registerCS"].ConnectionString))
{
    connection.Open();
    string sql1 = "Select pemgrp from Profile where userID = @username";
    string sql = "Select studname from Profile where pemgrp IN (" + sql1 + ")";
    SqlCommand command = new SqlCommand(sql, connection);
    command.Parameters.AddWithValue("@username", Session["username"].ToString());
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        //
    }
}