一个C#向SQL Server数据库保存图片的代码实例

数据库 SQL Server
本文主要介绍了用C#将图片保存到SQL Server数据库中的过程,并给出了全部的代码,希望能对读者有所帮助。

我们在用C#SQL Server数据库开发应用程序时,常常会用到图片处理的问题。那么C#是怎样将图片保存到SQL Server数据库中的呢?本文我们通过一个实例代码来介绍这一过程。

首先打开一个图片文件代码如下:

  1. private void Image(object sender, EventArgs e)  
  2.  
  3. {  
  4.  
  5. OpenFileDialog fileDialog = new OpenFileDialog();  
  6.  
  7. fileDialog.Filter = "图片文件|*.jpg";  
  8.  
  9. fileDialog.Multiselect = false;  
  10.  
  11. if (fileDialog.ShowDialog() == DialogResult.OK)  
  12.  
  13. {  
  14.  
  15. //图片地址  
  16.  
  17. this.textBoxImage.Text = fileDialog.FileName;  
  18.  
  19. }  
  20.  

保存图片:

  1. private void Save(object sender, EventArgs e)  
  2.  
  3. {  
  4.  
  5. //把图片转换为二进制保存  
  6.  
  7. Stream stream = new FileStream(this.textBoxImage.Text.Trim(), FileMode.Open);  
  8.  
  9. byte[] data=new byte[stream.Length];  
  10.  
  11. stream.Read(data, 0, data.Length);  
  12.  
  13. stream.Close();  
  14.  
  15. //保存到数据库  
  16.  
  17. string connectionString = 连接字符串;  
  18.  
  19. SqlConnection connection = new SqlConnection(connectionString);  
  20.  
  21. //sql语句  
  22.  
  23. string sql="@INSERT INTO 数据库名称 (Image) VALUES(@Image)";  
  24.  
  25. SqlCommand cmd = new SqlCommand(sql, connection);  
  26.  
  27. SqlParameter parameter=new SqlParameter ()  
  28.  
  29. {ParameterName="@Image",Value=data,SqlDbTypeSqlDbType=SqlDbType.Image};  
  30.  
  31. cmd.Parameters.AddRange(parameters);  
  32.  
  33. if (connection.State == ConnectionState.Closed)  
  34.  
  35. {  
  36.  
  37. connection.Open();  
  38.  
  39. }  
  40.  
  41. int count = cmd.ExecuteNonQuery();  
  42.  
  43. if (count > 0)  
  44.  
  45. {  
  46.  
  47. MessageBox.Show("success");  
  48.  
  49. }  
  50.  
  51. else  
  52.  
  53. {  
  54.  
  55. MessageBox.Show("failed");  
  56.  
  57. }  
  58.  
  59. connection.Close();  
  60.  
  61. }  
  62.  

 执行完上述代码,就可以成功地将图片保存到SQL Server数据库中了。

【编辑推荐】

  1. 浅析SQL Server数据库专用管理员连接DAC的使用
  2. 简述删除SQL SERVER 2000数据库日志的两种方法
  3. 在SQL SERVER 2005执行存储过程的权限分配问题
  4. 忘记sa密码,又删除了administrators帐号的解决方法
  5. T-SQL行列相互转换命令:PIVOT和UNPIVOT使用详解
责任编辑:赵鹏 来源: 博客园
相关推荐

2011-07-18 10:01:59

C# ADO.NETSQL Server数

2011-08-22 12:01:36

SQL Server代码优化

2011-07-20 13:40:00

SQLite数据库查询数据

2009-09-04 17:29:01

C#创建SQL Ser

2009-08-03 14:17:18

C#连接AccessC#连接SQL Ser

2011-07-20 12:55:17

SQLite数据库插入数据

2011-08-15 11:24:46

SQL Server事务

2011-04-11 14:18:44

SQL Server数图片

2011-07-20 14:57:47

SQLite数据库ORDER BYGROUP BY

2011-04-06 15:36:56

SQL Server数

2009-08-12 17:02:16

.NET向SQL Se

2010-06-28 09:53:11

SQL Server数

2011-04-06 11:34:52

SQL Server数查询优化

2009-07-30 18:18:27

C#时间计算

2011-07-26 18:06:00

SQL Server数批量重命名

2009-08-18 17:19:33

C#事件模型

2011-07-20 13:18:01

SQLite数据库修改和删除数据

2011-08-22 09:55:30

SQL Server 排序

2009-08-25 15:22:18

C#连接SQL数据库

2011-08-18 10:36:24

SQL ServerISNULL函数
点赞
收藏

51CTO技术栈公众号