如何从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();
}
}
答案 0 :(得分:2)
您需要在
中阅读更多内容.net - What is the C# Using block and why should I use it? - Stack Overflow
c# - SqlConnection.Close() inside using statement - Stack Overflow
更改
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")
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;
}
}
}