VB.NET 2008/VB - 데이터 액세스

MSSQL 2008에서 Image 데이터 읽고 쓰기

본클라쓰 2012. 7. 4. 16:54

 

MSSQL 2008 데이터베이스에 이미지를 읽고 쓰는 방법을 찾던 중, MSSQL에서 지원하는 파일스트림(FileStream)을 사용하기로 결정했었으나, 기존에 만들어진 데이터베이스에 FileStream를 추가하는 방법을 찾을 수 없었습니다. FileStream을 사용하기 위해서는 데이터베이스 생성시 지정을 해야 하는 것만 발견되어 구현방법을 바꾸기로 결정했습니다.

 

대안으로 Image 데이터 형을 사용하는 방법을 선택했는데, MSSQL 2008 도움말을 살펴보면 Image 데이터 형은 다음 버전에서 사라질 것이라고 합니다. 하지만 Image 데이터 형을 사용하는 방법으로 구현 방식을 결정했습니다. 가장 쉽게 구현이 가능할 것 같기 때문입니다.

 

 

데이터베이스 이미지 쓰지

 

Dim ofd As New OpenFileDialog
ofd.Filter = "jpg 파일(*.jpg)|*.jpg|gif 파일(*.gif)|*.gif|bmp 파일(*.bmp)|*.bmp"

If (Not ofd.ShowDialog = Windows.Forms.DialogResult.OK) Then
    Exit Sub
End If

 

Dim fileStream As New IO.FileStream(ofd.FileName, IO.FileMode.Open, IO.FileAccess.Read)
Dim len As Integer = fileStream.Length
Dim bt(len) As Byte
fileStream.Read(bt, 0, len)

 

Using connection As New SqlConnection(connectionString.ToString)
    connection.Open()

    Dim command As New SqlCommand("INSERT INTO TEST (USER_IMAGE) VALUES (@image)", connection)
    command.Parameters.AddWithValue("@image", bt)
    command.ExecuteNonQuery()

End Using

 

 

 

 

데이터베이스에 이미지 읽기

  

Using connection As New SqlConnection(cs.ToString)
    connection.Open()

    

    Dim command As New SqlCommand("SELECT USER_IMAGE FROM TEST WHERE IND = @index", connection)
    command.Parameters.AddWithValue("@index", 1)

    Dim reader As SqlDataReader = command.ExecuteReader

 

    If (reader.Read()) Then

        Dim img(0) As Byte
        img = reader.GetSqlBytes(0).Value

        Dim ms As IO.MemoryStream = New IO.MemoryStream(img)
        Me.PictureBox1.Image = Image.FromStream(ms)

    End If

End Using