[英]Insert records using ExecuteNonQuery, showing exception that invalid column name
我正在使用SQL Server 2008。
我想使用ExecuteNonQuery
将记录插入表中,因为我已经写了:
customUtility.ExecuteNonQuery("insert into furniture_ProductAccessories(Product_id, Accessories_id, SkuNo, Description1, Price, Discount) values(" + prodid + "," + strAcc + "," + txtSKUNo.Text + "," + txtAccDesc.Text + "," + txtAccPrices.Text + "," + txtAccDiscount.Text + ")");
&以下是ExecuteNonQuery
函数:
public static bool ExecuteNonQuery(string SQL)
{
bool retVal = false;
using (SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["dbConnect"].ToString()))
{
con.Open();
SqlTransaction trans = con.BeginTransaction();
SqlCommand command = new SqlCommand(SQL, con, trans);
try
{
command.ExecuteNonQuery();
trans.Commit();
retVal = true;
}
catch(Exception ex)
{
//HttpContext.Current.Response.Write(SQL + "<br>" + ex.Message);
//HttpContext.Current.Response.End();
}
finally
{
// Always call Close when done reading.
con.Close();
}
return retVal;
}
}
但是它显示异常,即Description1
无效列名 ,甚至是来自txtAccDesc.Text
的值。 我已经尝试通过删除Description1
列来成功插入其他记录。
我的心理调试能力告诉我,您正在文本框txtAccDesc
输入值Description1
。 连接SQL字符串时,您无法分隔文字值。
例如
"," + txtAccDesc.Text + "," +
应该
", '" + txtAccDesc.Text + "', " +
但是,这是一个不好的解决方案,因为它使您容易受到SQL注入攻击 (更不用说您需要在文字中处理引号和逗号),而应使用参数化查询 。
例如(警告写在记事本中,可能无法编译)
string SQL = "insert into furniture_ProductAccessories(Product_id,Accessories_id,SkuNo,Description1,Price,Discount) values(@Product_id,@Accessories_id,@SkuNo,@Description1,@Price,@Discount)"
SqlParameters[] parameters = new SQLParameters[6];
parameters[0] = new SqlParameter("@Product_id", SqlDbType.Int, prodid );
parameters[1] = new SqlParameter("@Accessories_id", SqlDbType.VarChar, strAcc );
parameters[2] = new SqlParameter("@SkuNo", SqlDbType.VarChar, txtSKUNo);
parameters[3] = new SqlParameter("@Description1", SqlDbType.VarChar, txtAccDesc.Text);
parameters[4] = new SqlParameter("@Price", SqlDbType.Money, txtAccPrices.Text);
parameters[5] = new SqlParameter("@Discount", SqlDbType.Money, txtAccDiscount.Text);
customUtility.ExecuteNonQuery(sql, paramters)
public static bool ExecuteNonQuery(string SQL, SqlParameters[] parameters)
{
bool retVal = false;
using (SqlConnection con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["dbConnect"].ToString()))
{
con.Open();
SqlTransaction trans = con.BeginTransaction();
SqlCommand command = new SqlCommand(SQL, con, trans);
cmd.parameters.AddRange(parameters);
try
{
command.ExecuteNonQuery();
trans.Commit();
retVal = true;
}
catch(Exception ex)
{
//HttpContext.Current.Response.Write(SQL + "<br>" + ex.Message);
//HttpContext.Current.Response.End();
}
// finally
//{
//Always call Close when done reading.
//con.Close(); Using already does this, so need for this
//}
return retVal;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.