2017-10-05 126 views
0

我有一個VB.NET項目與2 WinForms。現在在Form 1,我添加了一個PictureBox,一個Button,一個OpenFileDialog。我已經編碼按鈕來將圖片從PictureBox添加到SQL數據庫。現在我在Form 2有另一個picturebox。從數據庫檢索照片到PictureBox

所以我的問題是,如何從sql數據庫檢索圖像並將其顯示在圖片框中?

連接字符串如下:

Dim con As New SqlConnection 
con.ConnectionString = "Data source=" & My.Settings.sqlserver & "," & My.Settings.sqlport & 
         ";Network Library=DBMSSOCN;initial catalog=" & My.Settings.dbname & 
         ";User id=" & My.Settings.Username & 
         ";Password=" & My.Settings.Password & ";" 
Dim cmd As New SqlCommand("select * from userandadmins where Username = @username and Password = @password", con) 
con.Open() 
+2

請閱讀[問]並參加[旅遊]。您還需要在研究上取得更好的成績:您的頭銜會返回89,000次谷歌點擊量和1,980個SO帖子。 – Plutonix

回答

0

我使用Oracle存儲照片。您需要使用與存儲照片的字段類型相同的out參數來檢索照片。我假設這是一個BLOB。在將照片存儲在數據庫中之前,您必須將其轉換爲字節數組。由於這不是問題,所以我會發布我用來從Oracle數據庫檢索照片的代碼,轉換爲Sql Server代碼應該是一件簡單的事情。

我打開到數據庫的連接並將其傳遞給檢索函數。我返回包含一行數據,照片和其他識別信息的數據集。然後我將BLOB分配給一個變量,從那裏做你需要的。我用它做的是把它分配給一個圖像控件,它調用另一個aspx頁面來檢索照片(imageURL)。檢索它的代碼位於被調用的「Image.aspx」中,然後將照片返回給圖像控件。該HTML是在GetPhoto函數下面。這樣我就不需要將照片存儲在硬盤上的任何地方並找回它。

Dim MyConnection As New OracleConnection 
Dim MyDataSet As New DataSet 
Dim MyPhoto() As Byte = {} 

MyConnection = OpenConnection(Session("USERNAME"), Session("PASSWORD")) 

MyDataSet = GetPhoto(MyConnection, pPhotoID) 

myPhoto = MyDataSet.Tables("Data").Rows(0)("Photo") 

Public Function GetPhoto(ByVal TheConnection As OracleConnection, ByVal pPhotoID As String) As DataSet 
    Dim myCommand As New OracleCommand 
    Dim DS As New DataSet 
    Try 
     With myCommand 
      .Connection = TheConnection 
      .CommandText = "Darlington.PlayerSignUps.GetPhoto" 
      .CommandType = CommandType.StoredProcedure 
      .Parameters.Clear() 
      .Parameters.Add(New OracleParameter("pPhotoID", OracleDbType.Varchar2, pPlayerID.Length)).Value = pPhotoID 
      .Parameters.Add(New OracleParameter("pDataOut", OracleDbType.RefCursor)) 
      .Parameters(0).Direction = ParameterDirection.Input 
      .Parameters(1).Direction = ParameterDirection.Output 
      Dim DA As New OracleDataAdapter(myCommand) 
      DA.Fill(DS, "DATA") 
      GetPhoto = DS 
     End With 
    Catch exc As Exception 
     Throw New Exception("Error occured while retreiving photo from database, the error is: " & exc.Message) 
    End Try 
    myCommand = Nothing 

End Function 

<tr> 
    <td style="width: 372px; text-align: center"> 
     <asp:Image ID="Image_Photo" runat="server" ImageUrl="Image.aspx" /> 
    </td> 
</tr>