2013-08-02 1 views
2

나는 해결책을 찾고 있었지만 잘못하고있는 곳을 모른다. 그러나 나는 그것을 처음으로하고있다.이미지를 SQL 데이터베이스에 업로드

나는 클래스 학생들

class Students 
{ 

    public Image photo { get; set; } 


    public bool AddStudent(Students _student) 
    { 
     Settings mySettings = new Settings(); 

     SqlCeConnection conn = new SqlCeConnection(mySettings.StudentsConnectionString); 
     SqlCeCommand cmd = new SqlCeCommand(); 
     cmd.CommandType = System.Data.CommandType.Text; 
     cmd.Connection = conn; 
     cmd.CommandText = "insert into students (firstname, lastname, dob, allergic, allergydetails, memo, address, photo) " + 
          "Values (" + 
          "'" + @FirstName + "'," + 
          "'" + @LastName + "'," + 
          "'" + @Dob + "'," + 
          "'" + @isAllergic + "'," + 
          "'" + @AllergyDetails + "'," + 
          "'" + @Memo + "'," + 
          "'" + @photo + "'," + 
          "'" + @Address + "')"; 

     cmd.Parameters.Add("@FirstName", _student.FirstName); 
     cmd.Parameters.Add("@LastName", _student.LastName); 
     cmd.Parameters.Add("@Dob", _student.Dob); 
     cmd.Parameters.Add("@isAllergic", _student.isAllergic); 
     cmd.Parameters.Add("@AllergyDetails", _student.AllergyDetails); 
     cmd.Parameters.Add("@Memo", _student.Memo); 


     cmd.Parameters.Add("@photo", _student.photo); 

     cmd.Parameters.Add("@Address", _student.Address); 

     try 
     { 
      conn.Open(); 
      cmd.ExecuteNonQuery(); 
      conn.Close(); 
      return true; 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message.ToString()); 
      return false; 
     } 
     finally 
     { 
      if (conn.State == System.Data.ConnectionState.Open) conn.Close(); 
      cmd = null; 
     } 
    } 

지금 나는이 같은 내 양식에서 속성 값을 전달해야합니다.

private void btnAdd_Click(object sender, EventArgs e) 
     { 

      Students myStudent = new Students(); 

      myStudent.FirstName = txtFirstName.Text.Trim(); 
      myStudent.LastName = txtLastName.Text.Trim(); 
      myStudent.Dob = dtPicker1.Value; 
      myStudent.Memo = txtMemo.Text.Trim(); 
      myStudent.Address = txtAddress.Text.Trim(); 

      myStudent.photo = Image.FromFile(openFileDialog1.FileName); 

      // Insert New Record 
      if (myStudent.AddStudent(myStudent)) 
       MessageBox.Show("Student Added Successfully"); 


     } 

나는

에 매핑이 알려진 SqlCeType에 DbType과 System.Drawing.Bitmap에서 존재하지 않는 다음과 같은 오류를 얻고있다.

하지만 내가 왜 succedding하지 않는지 알 수 없습니다. 모든 제안은 높이 평가 될 것입니다. 이 링크 밖으로

+0

, 그것은 다음 이미지 데이터 형식 http://msdn.microsoft에 저장할 수 있습니다. com/en-us/library/ms172424.aspx –

+0

내 경험에 비추어 볼 때이 작업을 수행하는 동안 DB에서 BLOB 필드를 사용하고 BLOB 필드에 넣기 전에 이미지를 바이트 배열로 스트리밍해야합니다 . –

+0

당신은 이해가 안됩니다, 제 질문은 다릅니다. 먼저 클래스 인스턴스에 사진을 보관하고 DB에 업로드하고 있습니다. 예를 들어 openfiledialog.filename과 같은 기능이 없습니다. –

답변

4

이미지를 Byte[] 배열로 변환 한 다음 저장하십시오.

private void btnAdd_Click(object sender, EventArgs e) 
{ 
    Students myStudent = new Students(); 
    ... 
    ... 
    // change the student photo to byte array e.g. 
    // public byte[] Photo {get;set;} 
    myStudent.photo = imageToByteArray(Image.FromFile(openFileDialog1.FileName)); 
    ... 
    ... 
    // Insert New Record 
    if (myStudent.AddStudent(myStudent)) 
    MessageBox.Show("Student Added Successfully"); 
} 

// convert image to byte array 
public byte[] imageToByteArray(System.Drawing.Image imageIn) 
{ 
    MemoryStream ms = new MemoryStream(); 
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg); 
    return ms.ToArray(); 
} 

//Byte array to photo 
public Image byteArrayToImage(byte[] byteArrayIn) 
{ 
    MemoryStream ms = new MemoryStream(byteArrayIn); 
    Image returnImage = Image.FromStream(ms); 
    return returnImage; 
} 

참고 : 데이터베이스에서 데이터 형식이 image 유형을해야합니다

당신은 바이트 []로 이미지를 변환 할 필요가
+0

도와 주셔서 감사합니다.하지만 전혀 작동하지 않습니다. cmd.executenonQuery()에서이 오류 메시지가 나타납니다. 변환이 지원되지 않습니다. [변환 할 형식 (알려진 경우) = nvarchar, 변환 할 형식 (알려진 경우) = 이미지] " –

+0

DB의 사진 데이터 유형은 무엇입니까? – PawanS

+0

이미지입니다 .... –

0

프라하, 단 ..

http://www.codeproject.com/Articles/25956/Sending-Receiving-PictureBox-Image-in-C-To-From-Mi

당신이 정말로 데이터베이스에 이미지를 저장해야합니까?

폴더에 이미지를 저장 한 다음 (응용 프로그램에 업로드 한 경우)이 이미지의 경로를 "Varchar"필드에 데이터베이스에 저장하면 훨씬 적은 노력으로이 작업을 수행 할 수 있습니다. 웹 사이트에서 더 많은 작업을했는데 기본 사항이 제 생각과 동일해야합니다 ....

+0

그래, 지금해야 할 일이라고 생각합니다. 로컬 데이터베이스를 사용하는 데스크톱 기반 독립 실행 형 응용 프로그램입니다. 그래서 나는 그 이미지의 위치를 ​​저장하는 것이 더 나을 것이다. 또는 사용자가 해당 위치에서 이미지를 삭제하는 경우에도 해당 이미지를 내 정의 된 폴더에 복사 할 수 있습니다. –

관련 문제