[英]Upload text, image to database using textBox and fileUpload
问候所有我正在尝试使用C#创建一个asp.net网页,以上传有关产品的详细信息,其中包含产品名称,描述,图像和产品编号。
protected void btnSubmit_Click(object sender, EventArgs e)
{
string path = Server.MapPath("ProductsImages/");
if (FileUpload1.HasFile)
{
string ext = Path.GetExtension(FileUpload1.FileName);
if (ext == ".jpg" || ext == ".png")
{
FileUpload1.SaveAs(path + FileUpload1.FileName);
string name = "~/ProductsImages/" + FileUpload1.FileName;
string s = " insert into Products values('" + txtProductName.Text.Trim() + txtDescription.Text.Trim() + txtPrice.Text.Trim() + txtProductNumber.Text.Trim() + "','" + name + "')";
SqlCommand cmd = new SqlCommand(s, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Your File Has Been Uploaded");
}
else
{
Response.Write("You can upload only Jpg and png file");
}
}
else
{
Response.Write("Please Select an file To upload");
}
}
但是当我开始调试时,它向我显示错误:SqlException:列名或提供的值数与表定义不匹配。
但是,我的数据库设计是:列名| 数据类型名称nvarchar(50)说明nvarchar(50)价格nvarchar(50)图像图像Product_Number nvarchar(50)
我不知道在代码或数据库中哪里出了错?
在创建SQL命令的行上放置一个断点。 当达到断点时,检查变量s
的值。 您的问题将变得显而易见:您要做的就是将多个字段串联到一个字符串中。 如果将它们正确分割,它应该可以工作。
另一方面,无论如何您都不应该建立这样的查询。 使用SqlParameters正确生成和转义查询。
您的插入查询缺少逗号。
它应该是:
string s = " insert into Products values('" + txtProductName.Text.Trim() + "', '" + txtDescription.Text.Trim() + "', " + txtPrice.Text.Trim() + ", " + txtProductNumber.Text.Trim())";
不过,最好使用SqlParameter
做到这一点。 这是我的处理方式:
var queryInsert = "Insert Into Products Values (@productName, @productDescription, @productPrice, @productNumber)";
cmd.Parameters.AddWithValue("@productName", txtProductName.Text.Trim());
cmd.Parameters.AddWithValue("@productDescription", txtDescription.Text.Trim());
...你明白了。 您将像上面一样为每个参数设置参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.