How To Insert Image Into MySQL Database Using VbNet
In This VB.Net Tutorial We Will See How To Browse Picture On Button Click And Display The Selected Picture Into A PictureBox And Insert The Image From PictureBox Into MySQL DataBase Table Using MySqlCommand With Parameters In Visual Basic.Net Programming Language And Visual Studio Editor.
Project Source Code:
Imports MySql.Data.MySqlClient
Imports System.IO
Public Class Insert_Image_Into_MySQL
Dim connection As New MySqlConnection("datasource=localhost;port=3306;username=root;password=;database=s_t_d")
' browse and display image button
Private Sub ButtonSelect_Img_Click(sender As Object, e As EventArgs) Handles ButtonSelect_Img.Click
Dim opf As New OpenFileDialog
opf.Filter = "Choose Image(*.JPG;*.PNG;*.GIF)|*.jpg;*.png;*.gif"
If opf.ShowDialog = Windows.Forms.DialogResult.OK Then
PictureBox1.Image = Image.FromFile(opf.FileName)
End If
End Sub
' insert image button
Private Sub ButtonInsert_Click(sender As Object, e As EventArgs) Handles ButtonInsert.Click
Dim ms As New MemoryStream
PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
Dim command As New MySqlCommand("INSERT INTO `mypics`(`name`, `dscp`, `pic`) VALUES (@nm,@ds,@img)", connection)
command.Parameters.Add("@nm", MySqlDbType.VarChar).Value = TextBoxName.Text
command.Parameters.Add("@ds", MySqlDbType.VarChar).Value = TextBoxDesc.Text
command.Parameters.Add("@img", MySqlDbType.Blob).Value = ms.ToArray()
connection.Open()
If command.ExecuteNonQuery() = 1 Then
MessageBox.Show("Image Inserted")
Else
MessageBox.Show("Image Not Inserted")
End If
connection.Close()
End Sub
Private Sub Insert_Image_Into_MySQL_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
///////////////OUTPUT:
1 comments:
commentsNice tutorial, works well. It would be nice if there was one to extract that image from the MySql database and display it in a PictureBox. thanks well done
Reply