尝试将数据上传到数据库时"Column name or number of supplied values does not match table definition"



这是查询的C#代码(试图做到这一点,以便我可以将图像上传到我的数据库表(:

protected void ButtonInsert_Click(object sender, EventArgs e)
{
insert();
}
public void insert()
{
if (FileUpload1.PostedFile.FileName != "")
{
Byte[] image;
Stream s = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(s);
image = br.ReadBytes((Int32)s.Length);
string connectionString = @"Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=C:UserskfirmDesktopKEY_web_v1KEY_web_v1App_DataDatabase1.mdf;Integrated Security=True";
SqlConnection conn = new SqlConnection(connectionString);
//SqlConnection conn = new SqlConnection("data source=.\sqlexpress; initial catalog=SlideShow; integrated security=true");//ORIGINAL - "data source=.\sqlexpress; initial catalog=SlideShow; integrated security=true" //I think he's just making a dataset, I can edit later if it doesnt work or add this to the global.asax
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = "INSERT into Portfolio values(@ImageData)"; //I changed stuff!
comm.Parameters.AddWithValue("@ImageData", image); //I changed stuff!
conn.Open();
int row = comm.ExecuteNonQuery();
conn.Close();
if (row > 0)
{
LabelError.Text = "success";
}
}
else LabelError.Text = "please upload an image";
}

这是 HTML 代码:

<form  name="AddSiteToPortfolio" action="AddSiteToPortfolio.aspx" method="post" runat="server">
<table>
<tr>
<td>ImageData: </td>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="ButtonInsert" runat="server" Text="Upload Image" 
onclick="ButtonInsert_Click" />
<asp:Label ID="LabelError" runat="server" Text=""></asp:Label>
</tr>
</table>
</form>

这是我的表格代码:

CREATE TABLE [dbo].[Portfolio] (
[Image]       NVARCHAR (50) NOT NULL,
[Description] NVARCHAR (50) NOT NULL,
[ImageData] VARBINARY (max) NULL,
[id]          INT           IDENTITY (1, 1) NOT NULL,
PRIMARY KEY CLUSTERED ([id] ASC)
);

当我尝试更新(上传图像的二进制代码(数据库时,出现此错误:

列名或提供的值的数量与表定义不匹配。

源错误是粗体行:

conn.Open();
**int n = comm.ExecuteNonQuery();**
conn.Close();

怎么了?

如果您确实希望INSERT数据,则需要将实际值传递给表定义中标记为NOT NULL的所有列 - 除了自动生成的列(如"ID"(。

因此,您的插入查询应如下所示:

comm.CommandText = "INSERT INTO Portfolio (Image, Description, ImageData) VALUES(@Image, @Description, @ImageData)";

和参数:

comm.Parameters.AddWithValue("@Image", “myImage”);
comm.Parameters.AddWithValue("@Description", “WhateverYouNeed”);
comm.Parameters.AddWithValue("@ImageData", image);



或用于更新
如果要更新现有值,则需要一个标识符来定位要UPDATE的行和字段。在这种情况下,您需要要更新的图像的"ID"。

comm.CommandText = “UPDATE [Portfolio] SET [ImageData] = @Image WHERE [ID] = @ID”;

和参数:

comm.Parameters.AddWithValue("@Image", “myImage”);
comm.Parameters.AddWithValue(“@ID”, 123); // or whatever the ID

首先,您说当您的命令是插入时,您正在尝试更新。假设您的意思是插入,那么您的架构中有 2 列不是 NULL,因此必须传递这些列的值。您目前只传递"图像",即"图像数据",可以是 NULL,因此您还需要传入"图像"和"描述"的数据。

相关内容

  • 没有找到相关文章

最新更新