我有问题,当我计算从会话[“ email”]获得的电子邮件的数量列值时,在尝试捕获错误之前,我会尝试int count =(int)cmd.ExecuteScalar(); ,这是他们的错误消息“ System.Data.SqlClient.SqlConnection.OnError(SqlException异常时,'='附近的语法不正确。”。我需要从表中计算数量。menu_quantity的数据类型为float。
protected void Page_Load(object sender, EventArgs e)
{
if (Session["email"] != null)
{
A();
//lbltotalitemcart.Text = A().ToString();
}
else
{
lbltotalitemcart.Text = "login email first";
}
}
public int A()
{
String email = Request.QueryString["email"];
string stmt = "SELECT COUNT(menu_quantity) FROM cart Where email=" + email + "";
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["connectionString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(stmt, con))
{
con.Open();
int count = (int)cmd.ExecuteScalar();
return count;
}
}
}
catch (Exception e)
{
lbltotalitemcart.Text = e.ToString();
return 0;
}
}
答案 0 :(得分:5)
您在'
前后都错过了email
:
SELECT COUNT(menu_quantity) FROM cart Where email='" + email + "'";
但是,这不是执行查询的好方法。而是使用SqlCommand.Parameters
:
string stmt = "SELECT COUNT(menu_quantity) FROM cart Where email=@email"
using (SqlConnection con = new SqlConnection(ConfigurationManager.
ConnectionStrings["connectionString"].ConnectionString))
{
SqlCommand cmd = new SqlCommand(stmt, con)
cmd.Parameters.Add("@email", SqlDbType.VarChar).Value = email;
con.Open();
int count = (int)cmd.ExecuteScalar();
return count;
}
答案 1 :(得分:3)
我对ASP语法不太熟悉。但是我的直觉SQL知识告诉我您在查询本身中缺少电子邮件中的引号。