"'附近的语法不正确

use*_*598 2 c# sql asp.net

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

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();

        }
    }
Run Code Online (Sandbox Code Playgroud)

但是,当我运行时,它给我这个错误:关键字'where'附近的语法不正确.

描述:执行当前Web请求期间发生未处理的异常.请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息.

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

Ehs*_*san 8

因为你正在使用子查询

string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";
Run Code Online (Sandbox Code Playgroud)

应该

string sql = "Select studname from Profile where pemgrp in (" + sql1+ ")";
Run Code Online (Sandbox Code Playgroud)

并且您应该使用Parametereized查询来避免SQL注入.