i recieved error " connection must be valid and open" - mysql

Imports MySql.Data.MySqlClient
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim mstream As New System.IO.MemoryStream()
picture_me.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
mstream.Close()
Try
cmd = New MySqlCommand("insert into piccs(Photo,id) values(#image_data,#image_id")
cmd.Parameters.AddWithValue("#image_data", Nothing)
cmd.Parameters.AddWithValue("#image_id", arrImage)
cmd.ExecuteNonQuery()
MsgBox("saved")
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn()
End Sub
Private Sub browser_image_Click(sender As Object, e As EventArgs) Handles browser_image.Click
Me.find_image.FileName = Nothing
If find_image.ShowDialog() = DialogResult.OK Then
' Dim query1 As String
' cmd = New MySqlCommand
'cmd.Connection = connect
'query1 = "Insert into picss(id, Photo) values('" & TextBox1.Text & "','" & find_image.SafeFileNames(x) & "',#IMAGE,'" & Batch & "')"
If Not Me.find_image.FileName = Nothing Then
Me.picture_me.ImageLocation = find_image.FileName
End If
End If
End Sub
End Class

Related

ExecuteReader: Connection property has not been initialized visual studio

i'm new learning visual studio. and i get an error
Connection property has not been initialized
This my code:
Imports System.Data.SqlClient
Public Class Form1
Dim con As SqlConnection
Dim cm As SqlCommand
Dim dr As SqlDataReader
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
TextBox2.PasswordChar = ""
Else
TextBox2.PasswordChar = "•"
End If
End Sub
Private Sub Form1_Load(ByVal sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.MaxLength = 50
TextBox2.PasswordChar = "•"
End Sub
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Or TextBox2.Text = "" Then
MsgBox("pls fill the data", MsgBoxStyle.Information)
Exit Sub
Else
Call Koneksi()
cm = New SqlCommand("select*from login where username='" & TextBox1.Text & "'and password" & TextBox2.Text & "'", con)
cm.Connection = con
dr = cm.ExecuteReader
dr.Read()
last.Show()
Me.Close()
If dr.HasRows Then
MsgBox("succes", MsgBoxStyle.Information, "information")
Else
MsgBox("wrong password/username", MsgBoxStyle.Critical)
TextBox1.Clear()
TextBox2.Clear()
End If
End If
End Sub
End Class

Inserting images in mysql database with a longblob data type

Somebody check my code for inserting image into the database.I know there's some error but can't figure it out.When i run the code it worked but when i click the done button it always says NullReferenceException Here's What I've got
Imports MySql.Data.MySqlClient
Imports System.IO
Public Class adminreg
Dim con As MySqlConnection
Dim cmd As MySqlCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim reader As MySqlDataReader
Dim mstream As New System.IO.MemoryStream
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
mstream.Close()
con = New MySqlConnection
con.ConnectionString = "server=localhost;userid=root;password=1234;database=dat"
Try
con.Open()
Dim query As String
query = "insert into dat.login (idlogin,user,password,name,position,ownpic) values ('" & id.Text & "','" & usertxt.Text & "','" & passtxt.Text & "','" & nmetxt.Text & "','" & postxt.Text & "',#ownpic)"
cmd.Parameters.AddWithValue("#ownpic", arrImage)
cmd = New MySqlCommand(query, con)
reader = cmd.ExecuteReader
MessageBox.Show("Data Saved")
con.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
Private Sub adminreg_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
OpenFileDialog1.Filter = "imahe lang (*.jpg, *.bmp, *.png) | *.jpg; *.bmp; *.png| all files (*.*) | *.*"
If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Login.Show()
Me.Hide()
End Sub
End Class
Any Suggestion is highly appreciated Thank you...Just a beginner in VB.net
Private Sub pbStudentImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pbStudentImage.Click, txtStudentImage.Enter, txtStudentImage.Click
Try
Dim fileOpener As OpenFileDialog = New OpenFileDialog()
fileOpener.Filter = "Image files | *.jpg"
If fileOpener.ShowDialog() = Windows.Forms.DialogResult.OK Then
pbStudentImage.Image = Image.FromFile(fileOpener.FileName)
txtStudentImage.Text = fileOpener.FileName
End If
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
Private Sub btnSaveImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveImage.Click
Dim con As MySqlConnection = New MySqlConnection(ConString)
Dim cmd As MySqlCommand
Dim fs As FileStream
Dim br As BinaryReader
Try
If txtFirstName.Text.Length > 0 And txtStudentImage.Text.Length > 0 Then
Dim FileName As String = txtStudentImage.Text
Dim ImageData() As Byte
fs = New FileStream(FileName, FileMode.Open, FileAccess.Read)
br = New BinaryReader(fs)
ImageData = br.ReadBytes(CType(fs.Length, Integer))
br.Close()
fs.Close()
Dim CmdString As String = "INSERT INTO Students(FirstName, LastName, Image, Address) VALUES(#FirstName, #LastName, #Image, #Address)"
cmd = New MySqlCommand(CmdString, con)
cmd.Parameters.Add("#FirstName", MySqlDbType.VarChar, 45)
cmd.Parameters.Add("#LastName", MySqlDbType.VarChar, 45)
cmd.Parameters.Add(";#Image", MySqlDbType.Blob)
cmd.Parameters.Add("#Address", MySqlDbType.VarChar, 100)
cmd.Parameters("#FirstName").Value = txtFirstName.Text
cmd.Parameters("#LastName").Value = txtLastName.Text
cmd.Parameters("#Image").Value = ImageData
cmd.Parameters("#Address").Value = txtAddress.Text
con.Open()
Dim RowsAffected As Integer = cmd.ExecuteNonQuery()
If (RowsAffected > 0) Then
MsgBox("Image saved successfully!")
End If
con.Close()
Else
MsgBox("Incomplete data!", MsgBoxStyle.Critical, "")
End If
Catch ex As Exception
MsgBox(ex.ToString())
Finally
If con.State = ConnectionState.Open Then
con.Close()
End If
End Try
End Sub
Private Sub pbStudentImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pbStudentImage.Click, txtStudentImage.Enter, txtStudentImage.Click
Try
Dim fileOpener As OpenFileDialog = New OpenFileDialog()
fileOpener.Filter = "Image files | *.jpg"
If fileOpener.ShowDialog() = Windows.Forms.DialogResult.OK Then
pbStudentImage.Image = Image.FromFile(fileOpener.FileName)
txtStudentImage.Text = fileOpener.FileName
End If
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
Private Sub pbStudentImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles pbStudentImage.Click, txtStudentImage.Enter, txtStudentImage.Click
Try
Dim fileOpener As OpenFileDialog = New OpenFileDialog()
fileOpener.Filter = "Image files | *.jpg"
If fileOpener.ShowDialog() = Windows.Forms.DialogResult.OK Then
pbStudentImage.Image = Image.FromFile(fileOpener.FileName)
txtStudentImage.Text = fileOpener.FileName
End If
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
Private Sub btnSaveImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveImage.Click
Dim con As MySqlConnection = New MySqlConnection(ConString)
Dim cmd As MySqlCommand
Dim fs As FileStream
Dim br As BinaryReader

Edit Gridview columns to MySQL

When I try my code to update the GridViewBox to update to my database I get the following error message
Object Reference not set to an instance of an Object
But I cannot quite figure it out. Would appreciate any Help I can get.
Imports MySql.Data.MySqlClient
Public Class Form1
//GLOBAL DELARATION
Dim conString As String = "Server=xxx;" & "Database=xxx;" & "Uid=xxx;" & "xxx;"
Dim con As New MySqlConnection(conString)
Dim cmd As MySqlCommand
Dim adapter As MySqlDataAdapter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
//TODO: This line of code loads data into the 'OlejnaDataSet.people' table. You can move, or remove it, as needed.
Me.PeopleTableAdapter.Fill(Me.OlejnaDataSet.people)
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub hent()
Me.PeopleTableAdapter.Fill(Me.OlejnaDataSet.people)
End Sub
Private Sub cleartxt()
TextBox_name.Text = ""
TextBox_position.Text = ""
TextBox_team.Text = ""
End Sub
Private Sub Add()
Dim sql As String = "INSERT INTO people(Name,Position,Team) VALUES(#NAME,#POSITION,#TEAM)"
cmd = New MySqlCommand(sql, con)
//PARAMETERS
cmd.Parameters.AddWithValue("#NAME", TextBox_name.Text)
cmd.Parameters.AddWithValue("#POSITION", TextBox_position.Text)
cmd.Parameters.AddWithValue("#TEAM", TextBox_team.Text)
//Open Connection and INSERT
Try
con.Open()
If cmd.ExecuteNonQuery() > 0 Then
MsgBox("Added")
cleartxt()
End If
con.Close()
hent()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
//UPDATE DATABASE
Private Sub UpdateDG(id As String)
Dim sql As String = "UPDATE people SET name='" + TextBox_name.Text + "', position='" + TextBox_position.Text + "', team='" + TextBox_team.Text + "' WHERE ID='" + id + "'"
//Open CON, EXECUTE UPDATE, CLOSE
Try
con.Open()
adapter.UpdateCommand = con.CreateCommand()
adapter.UpdateCommand.CommandText = sql
If adapter.UpdateCommand.ExecuteNonQuery() > 0 Then
MsgBox("You have now updated")
cleartxt()
End If
con.Close()
//REFRESH
hent()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub ButtonAdd_Click(sender As Object, e As EventArgs) Handles ButtonAdd.Click
Add()
End Sub
Private Sub ButtonDelete_Click(sender As Object, e As EventArgs) Handles ButtonDelete.Click
End Sub
Private Sub ButtonUpdate_Click(sender As Object, e As EventArgs) Handles ButtonUpdate.Click
Dim id As String = DataGridView1.SelectedRows(0).Cells(0).Value
UpdateDG(id)
End Sub
Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick
Dim name As String = DataGridView1.SelectedRows(0).Cells(1).Value
Dim position As String = DataGridView1.SelectedRows(0).Cells(2).Value
Dim team As String = DataGridView1.SelectedRows(0).Cells(3).Value
TextBox_name.Text = name
TextBox_position.Text = position
TextBox_team.Text = team
End Sub
End Class
Hope you have clicked Update button without select any rows in your DataGrid
Change your Update Button Click Event as follows:
Private Sub ButtonUpdate_Click(sender As Object, e As EventArgs) Handles ButtonUpdate.Click
If DataGridView1.SelectedRows.Count > 0 Then
Dim id As String = DataGridView1.SelectedRows(0).Cells(0).Value
UpdateDG(id)
End If
End Sub
Update
Please Declare and Intialize your Sql Adapter
Use as below:
SqlDataAdapter adapter = new SqlDataAdapter();
//UPDATE DATABASE
Private Sub UpdateDG(id As String)
Dim sql As String = "UPDATE people SET name='" + TextBox_name.Text + "', position='" + TextBox_position.Text + "', team='" + TextBox_team.Text + "' WHERE ID='" + id + "'"
//Open CON, EXECUTE UPDATE, CLOSE
Try
SqlDataAdapter adapter = new SqlDataAdapter();
con.Open()
adapter.UpdateCommand = con.CreateCommand()
adapter.UpdateCommand.CommandText = sql
If adapter.UpdateCommand.ExecuteNonQuery() > 0 Then
MsgBox("You have now updated")
cleartxt()
End If
con.Close()
//REFRESH
hent()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub

i am not able to insert values in mysql table for vb.net

Imports MySql.Data.MySqlClient
Public Class Form1
Dim MysqlConn As MySqlConnection
Dim COMMAND As MySqlCommand
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.BrandsTableAdapter.Fill(Me.StoreDataSet.brands)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString =
"server=localhost;userid=root;password=;database=brands"
Dim READER As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "insert into database.brands(id,name,,created_at,updated_at) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "')"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
MessageBox.Show("Data saved")
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
End Class

save and retrive image from mysql using vb.net

This code is now working. i want to save an image in database please help me how i can work on this
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.ShowDialog()
TextBox1.Text = OpenFileDialog1.FileName
CaptionTextBox.Text = OpenFileDialog1.SafeFileName
' ImagePictureBox.Image = image.FromFile(TextBox1.Text)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
updateRecord("insert into uploadimages(caption,image) values('" + CaptionTextBox.Text + "', '#ImagePictureBox' )")
End Sub
Imports MySql.Data.MySqlClient
Imports System.Drawing.Imaging
Dim cn As New MySqlConnection
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
Dim da As MySqlDataAdapter
Dim dt As New DataTable
Dim abc As String
private sub from1()
cn.ConnectionString = "Server=localhost; user id=root; password=; database = school"
cmd.Connection = cn
cn.Open()
end sub
Private Sub images()
Dim arrImage() As Byte
Dim strImage As String
Dim myMs As New IO.MemoryStream
If Not IsNothing(Me.PictureBox5.Image) Then
Me.PictureBox5.Image.Save(myMs, Me.PictureBox5.Image.RawFormat)
arrImage = myMs.GetBuffer
strImage = "1000"
Else
arrImage = Nothing
strImage = "NULL"
End If
cmd.CommandText = "INSERT INTO admision(name, photo) VALUES('" & Me.TextBox1.Text & "'," & _
strImage & ")"
If strImage = "1000" Then
cmd.Parameters.Add(strImage, MySqlDbType.Blob).Value = arrImage
End If
MsgBox("Data save successfully!")
clear()
cmd.ExecuteNonQuery()
cn.Close()
End Sub