ASP.NET C#从数据库检索多个值并添加会话

时间:2019-01-06 03:49:06

标签: c# asp.net sql-server webforms

如何从SQL Server数据库中添加多个列值并将其插入session[]中?

FirstName正常工作时,添加LastName时出现错误。

string constr = sql connection here.... ;

using (SqlConnection con = new SqlConnection(constr))
{
    using (SqlCommand cmd = new SqlCommand("SELECT Email, [FirstName] FROM Personal WHERE Email = @email"), cmd2 = new SqlCommand("SELECT Email, [LastName] FROM Personal WHERE Email = @email"))
    {
        cmd.Parameters.AddWithValue("@email", TextboxUsr.Text);
        cmd.Connection = con;
        cmd2.Parameters.AddWithValue("@email", TextboxUsr.Text);
        cmd2.Connection = con;

        con.Open();

        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            if (sdr.Read())
            {
                string fName = sdr["FirstName"].ToString();
                //string lName = sdr["LastName"].ToString();

                string userFullName = fName;
                Session["New"] = userFullName;
            }
        }

        //con.Close();
    }
}

1 个答案:

答案 0 :(得分:2)

步骤01:了解有关SQL和C#基础知识的更多信息

您需要在

中阅读更多内容

步骤02:以正确的方式使用“选择”

  • 更改

    SqlCommand 
    cmd = new SqlCommand("SELECT Email, [FirstName] FROM Personal WHERE Email = @email"), 
    cmd2 = new SqlCommand("SELECT Email, [LastName] FROM Personal WHERE Email = @email"))
    
  • SqlCommand 
    cmd = new SqlCommand("SELECT Email, [FirstName],[LastName] FROM Personal WHERE Email = @email")
    

步骤03:读取完整代码

var sql = @"SELECT Email, [FirstName],[LastName] FROM Personal WHERE Email = @email";
using (var con = new SqlConnection(constr))
using (var cmd = new SqlCommand(sql, con))
{
    con.Open();
    cmd.Parameters.AddWithValue("@email", TextboxUsr.Text);
    using (var sdr = cmd.ExecuteReader())
    {
        if (sdr.Read())
        {
            var fName = sdr["FirstName"].ToString();
            var lName = sdr["LastName"].ToString();
            var userFullName = fName + " " + lName;
            Session["New"] = userFullName;
        }
    }
}