select 用户名等于会话的语句

select statement where username is equal to session

简单的问题,这个可以吗? Select ID 来自 Table where username = Session?

SqlCommand cm = new SqlCommand("select ID from CustomerDetails Where CustomerName ="Session["New"], con); - this has been solved.

第二题:

我想这样实现:

if (Session["New"] != reader["ID"].ToString())
            {
                Response.Redirect("NotAuthorized.aspx");
            }

在我的 if 语句中出现错误。有什么技巧吗?

完整代码在这里:

SqlConnection con = new SqlConnection(strConnString);
        con.Open();
        string str = "select ID from CustomerDetails Where CustomerName = '"+Session["New"].ToString()+"'";
        com = new SqlCommand(str, con);
        SqlDataReader reader = com.ExecuteReader();

        if (!IsPostBack)
        {
            if (Session["New"] != reader["ID"].ToString())
            {
                Response.Redirect("NotAuthorized.aspx");
            }
protected void Page_Load(object sender, EventArgs e)
{
        SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
        SqlCommand cmd = new SqlCommand("select ID from CustomerDetails ", conn);
        SqlDataAdapter da = new SqlDataAdapter("", conn);
 DataTable dt = new DataTable();
    da.fill(dt);
int count=dt.Rows.Count;
if (Count > 0)
{
for (int i = 0; i < Count; i++)
{
Label2.Text =dt1.Rows[i]["ID"].ToString();
}
}
}

试试这个

SqlCommand cm = new SqlCommand("select ID from CustomerDetails Where CustomerName ='"+Session["New"].ToString()+"'", con);
string ID =cm.ExecuteScalar().ToString();

假设,

会话["New"] 包含用户名(数据类型为字符串)

为了让你的代码更容易出错,我认为最好在你的 SQL 命令中使用命名参数,如下所示:

// suppose customer ID is an integer
int customerId = 0;
string customerName = (string)Session["New"];
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
    SqlCommand sqlCmd = new SqlCommand("SELECT id FROM CustomerDetails WHERE CustomerName = @customerName", sqlCon);
    sqlCmd.Parameters.AddWithValue("@customerName", customerName);
    object result = sqlCmd.ExecuteScalar();
    if (result != null)
        customerId = (int)result;
}