简体   繁体   English

C#:使用字节数组通过数据表对象将PictureBox图像保存到SQL Server数据库

[英]C#: Use byte array to save PictureBox images to SQL Server database through a datatable object

I am learning C# including interacting with SQL Server databases. 我正在学习C#,包括与SQL Server数据库进行交互。 I am stuck however, on adding PictureBox images programmatically to a SQL Server database: 但是,我被困在以编程方式将PictureBox图像添加到SQL Server数据库中:

I have created a form with text fields, a picture box, to display/edit/add single records to a database successfully and am successfully using all of the following: 我创建了一个带有文本字段,图片框的表单,以成功地将单个记录显示/编辑/添加到数据库,并且成功使用了以下所有功能:

DB Connection = RRConnection

SqlCommand object = playersCommand

SqlDataAdapter object = playersAdapter

dataTable object = playersTable

currencyManager = playerManager

PictureBox1 control = including a button to navigate filesystem and select/load jpeg image into form PictureBox1

Bindings like - txtName.DataBindings.Add("Text", playersTable, "Name") for text fields - I think I need to bind the picturebox1 IMage Byte Array but do not know how to do 像文本字段那样的绑定-txtName.DataBindings.Add(“ Text”,playersTable,“ Name”)-我想我需要绑定picturebox1 IMage字节数组,但不知道该怎么做

When the form closes, the table is loaded into the SQLServer database table tbl_BB into the column named "Image" of type image. 表单关闭后,该表将被加载到SQLServer数据库表tbl_BB中的image类型的名为“ Image”的列中。

I know I have to convert the image to a byte array to save, but am confused on how to bind the image byte array to the dataTable, allowing it to be uploaded to the database on form close. 我知道我必须将图像转换为字节数组以保存,但是在如何将图像字节数组绑定到dataTable上感到困惑,从而使其可以在窗体关闭时上传到数据库。 I've done a lot of googling on it but the solutions do not seem to match the code I am using... 我已经对其进行了很多搜索,但是解决方案似乎与我使用的代码不匹配...

Given the above, can you advise the code necessary for this? 鉴于以上所述,您能否建议为此所需的代码?

Don't use image it will be removed from MS SQL soon. 不要使用图像,它将很快从MS SQL中删除。 https://docs.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql https://docs.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql

Just use varbinary. 只需使用varbinary。

the general way to do it is: 通用的方法是:

1) SQL Server will have a varbinary(max) column. 1)SQL Server将具有一个varbinary(max)列。

2) Take the jpeg and convert it to a byte array 2)取jpeg并将其转换为字节数组

3) add the byte array as a paramter to your sql command object 3)将字节数组作为参数添加到sql命令对象

4) execute nonquery for insertion. 4)执行非查询插入。

May I suggest you merely save the image on disk directly, and reference the path to the image in the DB instead? 我是否可以建议您仅将映像直接保存在磁盘上,然后在数据库中引用该映像的路径? Saving images in a db is considered bad practice. 将图像保存在数据库中被认为是不好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM