且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何动态上传图像到SQL Server数据库?

更新时间:2023-02-08 16:30:35

甚至不尝试修改表格:这是错误的方法。

我假设您正在尝试添加列,因为您有与特定行相关的未知数量的图像,并认为为每个添加一列将做你想要的。它不会。添加列时,将其添加到表中的每一行 - 因此,如果您有一行需要20个图像的空间,那么每行都会获得该空间,即使它们只有一个图像。



相反,表格中没有任何行可以存储图像!

让我们假设这些是产品图片,并且产品可以有不同数量的图片 - 就像在eBay或亚马逊上出售的东西一样。

你有你的产品table:

Don't even try to modify the table: that's the wrong approach.
I assume you are trying to add columns because you have an unknown number of images related to a specific row, and think that adding a column for each will do what you want. It won't. When you add a column, you add it to every row in the table - so if you have one row which needs space for 20 images then every row gets that space, even if they have only one image.

Instead, don't have any rows in the table for storing images at all!
Lets assume these are product pictures, and that a product can have a variable number of images - just as something for sale on eBay or Amazon might.
You have your Products table:
ID              INT, IDENTITY (or UNIQUEIDENTIFIER, depending on your preference)
Title           NVARCHAR(255)
Description     NVARCHAR(MAX)
Price           DECIMAL(8,2)
Stock           INT

但不是添加IMAGE列,而是创建第二个表图像:

But instead of adding IMAGE columns, you create a second table Images:

ID              INT, IDENTITY (Or UNIQUEIDENTIFIER)
ProductID       Same as ID in the Products table, FOREIGN KEY to Products.ID
ImageData       IMAGE

然后您可以添加任意数量的图像因为您需要产品,并在需要时使用产品ID检索它们。

You can then add as many images as you need to a Product, and retrieve them using the Product ID when you need them.