WorkaHolic/MSSQL

Image DataBase(MSSQL) Inser & Select

2008. 3. 24. 18:09
반응형
 Visual C# .NET에서 ADO.NET을 사용하여 BLOB 데이터 읽고 쓰는 방법


원본 위치 <
http://support.microsoft.com/kb/309158/KO/>


프로젝트 만들기

1.

MyImages라는 테이블을 SQL Server Northwind 데이터베이스에 추가합니다. 테이블에 다음 필드를 포함시킵니다.

형식이 Int인 "ID"라는 필드

길이가 50이고 형식이 VarChar인 "Description"이라는 필드

형식이 Image인 "ImgField"라는 필드

2.

Visual Studio .NET을 시작한 다음 새로운 Visual C# Windows 응용 프로그램 프로젝트를 만듭니다.

3.

도구 상자에서 기본 폼 Form1로 두 Button 컨트롤을 끕니다.

4.

속성 창에서 Button1텍스트 속성을 Save to Database(from File)로 변경하고 Button2Text 속성을 Save to File(from Database)로 변경합니다.

5.

코드 창의 맨 위에 다음 코드를 추가합니다.

using System.Data;
using System.Data.SqlClient;
using System.IO;
                                       

6.

Button1을 두 번 누르고 다음 코드를 Button1_Click 이벤트 처리기에 추가합니다.


참고 Uid <user name>은 데이터베이스에서 이러한 작업을 수행할 권한을 갖고 있어야 합니다.

{
SqlConnection con = new SqlConnection("Server=Darkover;uid=<username>;pwd=<strong password>;database=northwind");
SqlDataAdapter da = new SqlDataAdapter("Select * From MyImages", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("MyImages");

da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
FileStream fs = new FileStream(@"C:\winnt\Gone Fishing.BMP", FileMode.OpenOrCreate, FileAccess.Read);
                       
byte[] MyData= new byte[fs.Length];
fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));
                       
fs.Close();
                       
da.Fill(ds,"MyImages");
                               
DataRow myRow;
myRow=ds.Tables["MyImages"].NewRow();

myRow["Description"] = "This would be description text";
myRow["imgField"] = MyData;
ds.Tables["MyImages"].Rows.Add(myRow);
da.Update(ds, "MyImages");

con.Close();
               
}
                                       

7.

Button2를 두 번 누르고 다음 코드를 Button2_Click 이벤트 처리기에 추가합니다.


참고 Uid <user name>은 데이터베이스에서 이러한 작업을 수행할 권한을 갖고 있어야 합니다.

{
SqlConnection con = new SqlConnection("Server=Darkover;uid=<username>;pwd=<strong password>;database=northwind");
SqlDataAdapter da = new SqlDataAdapter("Select * From MyImages", con);
SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
DataSet ds = new DataSet("MyImages");

byte[] MyData= new byte[0];
                       
da.Fill(ds, "MyImages");
DataRow myRow;
myRow=ds.Tables["MyImages"].Rows[0];
          
MyData =  (byte[])myRow["imgField"];
int ArraySize = new int();
ArraySize = MyData.GetUpperBound(0);

FileStream fs = new FileStream(@"C:\winnt\Gone Fishing2.BMP", FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(MyData, 0,ArraySize);
fs.Close();
}
                                       

8.

F5 키를 눌러 응용 프로그램을 컴파일하고 실행합니다.

9.

Save to Database(from File)를 눌러 이미지 C:\WinNT\Gone Fishing.bmp를 SQL Server Image 필드로 로드합니다.

10.

Save to File(from Database)을 눌러 SQL Server Image 필드의 데이터를 파일로 저장합니다.



데이터베이스에서 Visual C#의 PictureBox 컨트롤로 그림 직접 복사

 

원본 위치 <http://support.microsoft.com/kb/317701/ko>

 

예제

1.

구조가 다음과 같은 SQL Server나 Access 테이블을 만듭니다.

CREATE TABLE BLOBTest
(
BLOBID INT IDENTITY NOT NULL,
BLOBData IMAGE NOT NULL
)
                                       

2.

Visual Studio .NET을 열고 새 Visual C# Windows 응용 프로그램 프로젝트를 만듭니다.

3.

도구 상자에서 기본 Form1에 PictureBox와 두 Button 컨트롤을 추가합니다. Button1의 Text 속성을 File to Database로 설정하고 Button2의 Text 속성을 Database to PictureBox로 설정합니다.

4.

폼의 코드 모듈 맨 위에 다음 using 문을 삽입합니다.

using System.Data.SqlClient;
using System.IO;
using System.Drawing.Imaging;
                                       

5.

public class Form1 : System.Windows.Forms.Form 클래스 선언 안에 데이터베이스 연결 문자열에 대한 다음 선언을 추가하고 필요한 경우 연결 문자열을 조정합니다.

    String strCn = "Data Source=localhost;integrated security=sspi;initial catalog=mydata";
                                       

6.

Button1(File to Database)의 Click 이벤트 프로시저에 다음 코드를 삽입합니다. 필요한 경우 사용할 수 있는 샘플 이미지 파일의 파일 경로를 조정합니다. 이 코드는 디스크에서 Byte 배열로 이미지를 읽은 다음(FileStream 개체 사용) 이 데이터를 매개 변수화된 Command 개체를 사용하여 데이터베이스에 삽입합니다.

try
{
        SqlConnection cn = new SqlConnection(strCn);
        SqlCommand cmd =  new SqlCommand("INSERT INTO BLOBTest (BLOBData) VALUES (@BLOBData)", cn);
        String strBLOBFilePath = @"C:\blue hills.jpg";//Modify this path as needed.

        //Read jpg into file stream, and from there into Byte array.
        FileStream fsBLOBFile =  new FileStream(strBLOBFilePath,FileMode.Open, FileAccess.Read);
        Byte[] bytBLOBData = new Byte[fsBLOBFile.Length];
        fsBLOBFile.Read(bytBLOBData, 0, bytBLOBData.Length);
        fsBLOBFile.Close();

        //Create parameter for insert command and add to SqlCommand object.
        SqlParameter prm = new  SqlParameter("@BLOBData", SqlDbType.VarBinary, bytBLOBData.Length, ParameterDirection.Input, false,
                                0, 0, null, DataRowVersion.Current, bytBLOBData);
        cmd.Parameters.Add(prm);

        //Open connection, execute query, and close connection.
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
}catch(Exception ex)
{MessageBox.Show(ex.Message);}
                                       

7.

Button2(Database to PictureBox)의 Click 이벤트 프로시저에 다음 코드를 삽입합니다. 이 코드는 데이터베이스의 BLOBTest 테이블에서 DataSet로 행을 가져오고 가장 최근에 추가된 이미지를 Byte 배열로 복사한 다음 MemoryStream 개체로 복사하고 MemoryStreamPictureBox 컨트롤의 Image 속성으로 로드합니다.

try
{
        SqlConnection cn = new SqlConnection(strCn);
        cn.Open();

        //Retrieve BLOB from database into DataSet.
        SqlCommand cmd = new SqlCommand("SELECT BLOBID, BLOBData FROM BLOBTest ORDER BY BLOBID", cn);        
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds, "BLOBTest");
        int c = ds.Tables["BLOBTest"].Rows.Count;

        if(c>0)
        {   //BLOB is read into Byte array, then used to construct MemoryStream,
                //then passed to PictureBox.
                Byte[] byteBLOBData =  new Byte[0];
                byteBLOBData = (Byte[])(ds.Tables["BLOBTest"].Rows[c - 1]["BLOBData"]);
                MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
                pictureBox1.Image= Image.FromStream(stmBLOBData);
        }
        cn.Close();
}
catch(Exception ex)
{MessageBox.Show(ex.Message);}
                                       

8.

F5 키를 눌러 프로젝트를 컴파일하고 실행합니다.

9.

File to Database 단추를 눌러서 최소한 하나 이상의 예제 이미지를 데이터베이스로 로드합니다.

10.

Database to PictureBox 단추를 눌러 PictureBox 컨트롤에 저장된 이미지를 표시합니다.

11.

PictureBox 컨트롤에서 데이터베이스로 직접 이미지를 삽입할 수 있으려면 세 번째 Button 컨트롤을 추가하고 Click 이벤트 프로시저에 다음 코드를 삽입합니다. 이 코드는 PictureBox 컨트롤에서 MemoryStream 개체로 이미지 데이터를 가져오고 MemoryStreamByte 배열로 복사한 다음 매개 변수화된 Command 개체를 사용하여 Byte 배열을 데이터베이스에 저장합니다.

try
{
        SqlConnection cn = new SqlConnection(strCn);
        SqlCommand cmd = new SqlCommand("INSERT INTO BLOBTest (BLOBData) VALUES (@BLOBData)", cn);

        //Save image from PictureBox into MemoryStream object.
        MemoryStream ms  = new MemoryStream();
        pictureBox1.Image.Save(ms, ImageFormat.Jpeg);

        //Read from MemoryStream into Byte array.
        Byte[] bytBLOBData = new Byte[ms.Length];
        ms.Position = 0;
        ms.Read(bytBLOBData, 0, Convert.ToInt32(ms.Length));

        //Create parameter for insert statement that contains image.
        SqlParameter prm = new SqlParameter("@BLOBData", SqlDbType.VarBinary, bytBLOBData.Length, ParameterDirection.Input, false,
                                        0, 0,null, DataRowVersion.Current, bytBLOBData);
        cmd.Parameters.Add(prm);
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
}catch(Exception  ex)
 {MessageBox.Show(ex.Message);}
                                       

12.

프로젝트를 실행합니다. Database to PictureBox 단추를 눌러 PictureBox 컨트롤에 이전에 저장한 이미지를 표시합니다. 새로 추가된 단추를 눌러 PictureBox에서 데이터베이스로 이미지를 저장합니다. 그런 다음 Database to PictureBox 단추를 다시 눌러서 이미지가 제대로 저장되었는지 확인합니다.


===================================================================================================

How to Store or Save Image in SQL Server table

원본 위치 <http://www.shabdar.org/store-save-images-in-sql-server.html>

To store an image in to sql server, you need to read image file into a byte array. Once you have image data in byte array, you can easity store this image data in sql server using sql parameters. Following code explains you how to do this.

        
private void cmdSave_Click(object sender, EventArgs e)
{
    try
    {
        //Read Image Bytes into a byte array
        byte[] imageData = ReadFile(txtImagePath.Text);

        //Initialize SQL Server Connection
        SqlConnection CN = new SqlConnection(txtConnectionString.Text);

        //Set insert query
        string qry = "insert into ImagesStore (OriginalPath,ImageData) _
                                    values(@OriginalPath, @ImageData)";

        //Initialize SqlCommand object for insert.
        SqlCommand SqlCom = new SqlCommand(qry, CN);

        //We are passing Original Image Path and 
        //Image byte data as sql parameters.
        SqlCom.Parameters.Add(new SqlParameter("@OriginalPath", 
                                    (object)txtImagePath.Text));
                                    
        SqlCom.Parameters.Add(new SqlParameter("@ImageData", 
                                            (object)imageData));

        //Open connection and execute insert query.
        CN.Open();
        SqlCom.ExecuteNonQuery();
        CN.Close();

        //Close form and return to list or images.
        this.Close();
    }
   

Following code explains how to read image file in to a byte array.

        
    //Open file in to a filestream and 
    //read data in a byte array.
    byte[] ReadFile(string sPath)
    {
        //Initialize byte array with a null value initially.
        byte[] data = null;

        //Use FileInfo object to get file size.
        FileInfo fInfo = new FileInfo(sPath);
        long numBytes = fInfo.Length;

        //Open FileStream to read file
        FileStream fStream = new FileStream(sPath, FileMode.Open, 
                                                FileAccess.Read);

        //Use BinaryReader to read file stream into byte array.
        BinaryReader br = new BinaryReader(fStream);

        //When you use BinaryReader, you need to 
//supply number of bytes to read from file. //In this case we want to read entire file.
//So supplying total number of bytes. data = br.ReadBytes((int)numBytes); return data; }

How to read image data bytes from SQL Server table

To read images from SQL Server, prepare a dataset first which will hold data from SQL Server table. Bind this dataset with a gridview control on form.

    void GetImagesFromDatabase()
    {
        try
        {
            //Initialize SQL Server connection.
            SqlConnection CN = new SqlConnection(txtConnectionString.Text);

            //Initialize SQL adapter.
            SqlDataAdapter ADAP = new SqlDataAdapter("Select * from ImagesStore", CN);

            //Initialize Dataset.
            DataSet DS = new DataSet();

            //Fill dataset with ImagesStore table.
            ADAP.Fill(DS, "ImagesStore");

            //Fill Grid with dataset.
            dataGridView1.DataSource = DS.Tables["ImagesStore"];
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

   

Once you have image data in grid, get image data from grid cell. Alternatively you can also get image data from Dataset table cell.

            //Store image to a local file.
            pictureBox1.Image.Save("c:\test_picture.jpg",
System.Drawing.Imaging.ImageFormat.Jpeg);

If you want you can extend this code to save image from Picture Box to a local image file.

    //Store image to a local file.
pictureBox1.Image.Save("c:\test_picture.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);

Points of Interest

If you see frmImageStore in design mode, I have placed picturebox1 into a panel. This panel's AutoScroll property is set to True and SizeMode property of PictureBox1 is set to True. This allows picturebox to resize itself to the size of original picture. When picturebox's size is more than Panel1's size, scrollbars becomes active for Panel.

반응형