Created
January 5, 2019 15:02
-
-
Save TanmayChakrabarty/2dc78b5423929e1824e33679730d14e0 to your computer and use it in GitHub Desktop.
Saving images in MySQL Database from Visual Basic .NET 2010
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Imports | |
MySql.Data | |
Public Class Form1 | |
Dim sql As String | |
Dim sql_connection As MySqlClient.MySqlConnection | |
Dim sql_command As MySqlClient.MySqlCommand | |
Dim sql_reader As MySqlClient.MySqlDataReader | |
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load | |
sql_connection = New MySqlClient.MySqlConnection("Data Source=localhost;user id=root;database=my_test_projects;") | |
Try | |
sql_connection.Open() | |
Catch ex As Exception | |
MsgBox("Error Creating DB Connection") | |
End Try | |
End Sub | |
Private Sub btn_save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_save.Click | |
Dim FileSize As UInt32 | |
Dim mstream As New System.IO.MemoryStream() | |
pic_box_save.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg) | |
Dim arrImage() As Byte = mstream.GetBuffer() | |
FileSize = mstream.Length | |
mstream.Close() | |
MsgBox(FileSize) | |
Try | |
sql = "INSERT INTO image_in_db(id, image_data) VALUES(@image_id, @image_data)" | |
sql_command = New MySqlClient.MySqlCommand(sql, sql_connection) | |
sql_command.Parameters.AddWithValue("@image_id", Nothing) | |
sql_command.Parameters.AddWithValue("@image_data", arrImage) | |
sql_command.ExecuteNonQuery() | |
Catch ex As Exception | |
MsgBox(ex.Message) | |
Exit Sub | |
End Try | |
MsgBox("Image has been saved.") | |
End Sub | |
Private Sub btn_get_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_get.Click | |
Dim arrImage() As Byte | |
Try | |
sql = "SELECT * FROM image_in_db WHERE id = '1'" | |
sql_command = New MySqlClient.MySqlCommand(sql, sql_connection) | |
sql_reader = sql_command.ExecuteReader() | |
sql_reader.Read() | |
arrImage = sql_reader.Item("image_data") | |
Dim mstream As New System.IO.MemoryStream(arrImage) | |
pic_box_get.Image = Image.FromStream(mstream) | |
sql_reader.Close() | |
Catch ex As Exception | |
MsgBox(ex.Message) | |
Exit Sub | |
End Try | |
End Sub | |
End Class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment