日期:2010-10-09 浏览次数:20432 次
时我们需要把一些大的数据对象如图片、可执行文件、视频和文档等数据存入数据库。在MS SQL Server中,这要用到Image数据类型,可以保存多达2G的数据。以下给出一个通过ADO.NET和MS SQL Server实现的小小的例子。
先创建一个测试数据表。
在查询分析器中输入并执行以下语句:
Create table [imgtable](
[imgid] [int] IDENTITY(1,1) NOT NULL,
[imgname] [varchar](100) COLLATE Chinese_PRC_CI_AS NULL,
[imgData] [image] NULL,
PRIMARY KEY CLUSTERED
(
[imgid]
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
这要在你所选的数据库中就多了一个名叫imgtable的表。
VS中的代码如下:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace ADO_Demo
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class ADO_Demo : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.Button button3;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
public ADO_Demo()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.button3 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(368, 48);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(104, 23);
this.button1.TabIndex = 0;
this.button1.Text = "保存图片";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(368, 120);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(104, 23);
this.button2.TabIndex = 1;
this.button2.Text = "显示图片";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// pictureBox1
//
this.pictureBox1.Location = new System.Drawing.Point(8, 16);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(312, 288);
this.pictureBox1.TabIndex = 2;
this.pictureBox1.Tab