The connection property has not been set or is null - mysql

When I run this function
For RepeatBooking = 1 To 51
dateConvertedDateToBook = dateDateToBook.Date
dateDateToBook = dateDateToBook.AddDays(7)
strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")
Try
Dim command As MySqlCommand = New MySqlCommand
Dim sqlQuery As String = "INSERT INTO bookings SET Date=" & "'" & strDateToBook & "',RoomID='" & strComputerRoomToBook & "',Length='" & intNewBookingLength & "',Period='" & intNewStartPeriod & "',UserID='" & intid & "'"
Dim reader As MySqlDataReader
SQLConnection.Open()
command.CommandText = sqlQuery
command.Connection = SQLConnection
reader = command.ExecuteReader
SQLConnection.Close()
Catch excep As Exception
MsgBox(excep.ToString)
End Try
Next
in my program I get an error saying "The connection property has not been set or is null"
How can I get rid of this?
It goes to the exception when it gets to SQLconnection.Open()
I created the ServerString and MySQL connection at the top of the module like so:
Dim ServerString As String = "Server=localhost;User Id=root;Password=**********;Database=rooms"
Dim SQLConnection As MySqlConnection = New MySqlConnection

You are opening a connection without its property
It should be,
Dim SQLConnection As New MySqlConnection(ServerString)
SQLConnection.Open
Also, you may want to use the USING function so that your connection is properly closed.
It seems you are just inserting a bunch of values to your database and not retrieving anything so why do you use a DataReader?
Your code should be something like this:
Using SQLConnection = New MySqlConnection(ServerString)
SQLConnection.Open 'You should open a connection only once
For RepeatBooking = 1 To 51
dateConvertedDateToBook = dateDateToBook.Date
dateDateToBook = dateDateToBook.AddDays(7)
strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")
Try
Dim sqlQuery As String = "INSERT INTO bookings SET " & _
"Date='" & strDateToBook & "'," & _
"RoomID='" & strComputerRoomToBook & "', " & _
"Length='" & intNewBookingLength & "', " & _
"Period='" & intNewStartPeriod & "', " & _
"UserID='" & intid & "'"
Dim command = New MySqlCommand(sqlQuery, SQLConnection)
command.ExecuteNonQuery
Catch excep As Exception
MsgBox(excep.Message)
End Try
Next
End Using
Also, you may want to change how to pass your values into a parameter. This will prevent SQL Injection.

Related

How can I increment from 1st to 2nd to 3rd when an existing Data is present in VB.net/Mysql

Seriously need help. Been figuring this one out for days and I can't seem to get it. Tried all the codes I searched but still no luck.
So here's the problem, for every added existing violation in a student in tablestudentviolation, The numberofviolation will increase from 1st to 2nd to 3rd. How can I do that? I'll post my codes (current in progress codes) and screenshot of the mysql table below for reference
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Mysqlconn = New MySqlConnection
Mysqlconn.ConnectionString =
"server=localhost;uid=root;password=;database=cdm"
Try
Mysqlconn.Open()
Dim query As String
query = "select * from cdm.tablestudentviolations where NameOfViolation = '" & ComboBox1.Text & "' and NumberOfViolation = LAST_INSERT_ID()"
command = New MySqlCommand(query, Mysqlconn)
Dim reader As MySqlDataReader = command.ExecuteReader
If reader.HasRows Then
command = New MySqlCommand(query, Mysqlconn)
reader = command.ExecuteReader
Else
Dim query1 As String
Dim reader1 As MySqlDataReader
Dim command1 As MySqlCommand
query1 = "insert into cdm.tablestudentviolations (StudentNumber,NameOfViolation,Remarks,NumberOfViolation,EmployeeUsername,EmployeeID) values ('" & Studnum.Text & "','" & ComboBox1.Text & "','" & RichTextBox1.Text & "','" & Label2.Text & "', '" & Form5.Label4.Text & "','2')"
command1 = New MySqlCommand(query1, Mysqlconn)
reader1 = command1.ExecuteReader
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

how to update picture in mysql database

i have tried this code here to insert and show picture from database to picturebox : stackoverflow.com/questions/5624760/store-picture-to-database-retrieve-from-db-into-picturebox
and yeah, it is working , but when i tried to do update using the same syntax as insert it got this error :
this is the insert syntax i use :
Dim FileSize As UInt32
Dim mstream As New System.IO.MemoryStream()
gambar.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
FileSize = mstream.Length
mstream.Close()
call konek
strSQL = "insert into tbmahasiswa VALUES ('" & _
txtNIM.Text & "','" & _
txtNama.Text & "','" & _
Format(dtpTanggal.Value, "yyyy-MM-dd") & "','" & _
txtAlamat.Text & "','" & _
cboJurusan.Text & "',#gambar)"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
.Parameters.AddWithValue("#gambar", arrImage)
.ExecuteNonQuery()
End With
and this the code i use to show picture from database to picture box :
Dim imgData As Byte()
call konek
strSQL = "select * from tbMahasiswa where NIM ='" & txtNIM.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
Using rd = com.ExecuteReader
rd.Read()
If rd.HasRows Then
txtNama.Text = rd.Item(1)
dtpTanggal.Value = rd.Item(2)
txtAlamat.Text = rd.Item(3)
imgData = TryCast(rd.Item(5), Byte())
If imgData IsNot Nothing Then
Using ms As New MemoryStream(imgData)
gambar.Image = CType(Image.FromStream(ms), Image)
End Using
End If
End If
End Using
Both Insert and Retrieving Picture Code above is Working ! , and then i use this code for update :
Dim FileSize As UInt32
Dim mstream As New System.IO.MemoryStream()
gambar.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
FileSize = mstream.Length
mstream.Close()
call konek
strSQL = "update tbmahasiswa set Nama ='" & txtNama.Text & _
"', TglLahir ='" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"', Alamat ='" & txtAlamat.Text & _
"', Jurusan ='" & cboJurusan.Text & _
"', gambar =' #gambar" & _
"' where NIM ='" & txtNIM.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
.Parameters.AddWithValue("#gambar", arrImage)
.ExecuteNonQuery()
End With
and then i got the error like in the picture above, all other data is correctly saved except the picture, it become some unknown file blob 8 KB size.
i'm still newbie at insert , update, delete picture in VB, please can you tell me what is wrong with the Update syntax code , is it already true but i'm missing something ? or is it totally wrong with the syntax ? please i need your guide here...
UPDATE :
actually there is "call konek" above "STRSQL" in the code, "konek" have the code for open the mysql connection,i put it in the separate module, here the full code in my module :
Module modKoneksi
Public conn As New MySql.Data.MySqlClient.MySqlConnection
Public rd As MySql.Data.MySqlClient.MySqlDataReader
Public com As MySql.Data.MySqlClient.MySqlCommand
Public strSQL As String
Public Sub konek()
conn.Close()
strSQL = "server='localhost';user='root';pwd='';database='dbsekolah';"
Try
conn.ConnectionString = strSQL
conn.Open()
Catch ex As MySql.Data.MySqlClient.MySqlException
MsgBox(ex.Message)
End
End Try
End Sub
End Module
hope this makes you easier to solve my problem
I know its late but this is the working code for me :
For retrieving the record from database with pictures :
Call konek() 'Call the connection module'
strSQL = "select * from tbMahasiswa where ID ='" & txtID.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
Using rd = com.ExecuteReader
rd.Read()
If rd.HasRows Then
txtNIM.Text = rd.Item(1)
txtNama.Text = rd.Item(2)
dtpTanggal.Value = rd.Item(3)
txtAlamat.Text = rd.Item(4)
imgData = TryCast(rd.Item(6), Byte())
If imgData IsNot Nothing Then
Using ms As New MemoryStream(imgData)
gambar.Image = CType(Image.FromStream(ms), Image)
End Using
End If
cboJurusan.SelectedIndex = cboJurusan.FindStringExact(rd.Item(5))
End If
End Using
For inserting record to database with pictures :
Call konek()
strSQL = "Insert Into tbmahasiswa Values ('" & txtID.Text & _
"','" & txtNIM.Text & _
"','" & txtNama.Text & _
"','" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"','" & txtAlamat.Text & _
"','" & cboJurusan.Text & _
"',#gambar)"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
If opdGambar.FileName = Nothing Then 'opdGambar is a PictureBox name'
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes("man-icon.png") 'Insert field gambar using an existing file in debug folder if file does not exist in PictureBox'
Else
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes(opdGambar.FileName) 'Insert field gambar using an existing file in PictureBox'
End If
com.ExecuteNonQuery()
End With
For updating record to database with pictures :
Call konek()
Dim adapter As New MySql.Data.MySqlClient.MySqlDataAdapter("select gambar from tbmahasiswa where ID='" & txtID.Text & "'", conn)
Dim dt As New DataTable("gambar")
adapter.Fill(dt)
strSQL = "update tbmahasiswa set NIM='" & txtNIM.Text & _
"',Nama='" & txtNama.Text & _
"',TglLahir='" & Format(dtpTanggal.Value, "yyyy-MM-dd") & _
"',Alamat='" & txtAlamat.Text & _
"',Jurusan='" & cboJurusan.Text & _
"' ,Gambar=#gambar where id='" & txtID.Text & "'"
com = New MySql.Data.MySqlClient.MySqlCommand(strSQL, conn)
With com
If opdGambar.FileName = Nothing Then
Dim row As DataRow = dt.Rows(0)
Using ms As New IO.MemoryStream(CType(row(0), Byte()))
Dim img As Image = Image.FromStream(ms)
gambar.Image = img
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = (CType(row(0), Byte())) 'field gambar will use the current existing file in database if PictureBox does not have a file'
End Using
Else
.Parameters.Add(New MySql.Data.MySqlClient.MySqlParameter("#gambar", MySql.Data.MySqlClient.MySqlDbType.LongBlob)).Value = IO.File.ReadAllBytes(opdGambar.FileName)
End If
com.ExecuteNonQuery()
End With
i hope for those who find the other answer a little confusing (like me), will find this answer helpful.

My code is not working. Am I doing it right?

What I want to achieve is:
I will choose what column should I update, this is why I am experimenting on my code but did not work and now I think I need some help.
Dim btnup="col1"
Dim btnval="1"
Try
Dim mysqlconn As New MySqlConnection
Dim conStr As String
conStr = "Server=localhost; user id=root; password=; database=dnc_floor"
mysqlconn = New MySqlConnection(conStr)
mysqlconn.Open()
Dim update As String
Dim cmd As MySqlCommand
update = "Update floor set ='" & btnup & "'=btnval where ID='" & Day & "'"
cmd = New MySqlCommand(update, mysqlconn)
cmd.ExecuteNonQuery()
Dim check As String = cmd.ExecuteNonQuery()
MsgBox("Saved")
mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show("Check your connection with your database")
Finally
mysqlconn.Dispose()
End Try
The update string is probably wrong. Maybe u think of that:
update = "Update floor set " & btnup & " ='" & btnval & "' where ID= '" & Day & "'"

Inserting query results from MS SQL 2008 to MYSQL via VB2010

Im a newbie in VB2010 & in MYSQL Database.
I have 2 database one on MS SQL 2008 (BigData) and another on Mysql. I have written some code in VB2010 to fetch data from SQL2008 and insert into MySQL. My goal is to transfer all data from MS SQL to MySQL as quick as I can thats why I created a simple vb script that will act as middleware to transfer data from MS SQL to MySQL.
My Headache is, almost 1 hour to transfer the 28,000 records from MS SQL to MySQL database. Is there any easiest way to transfer the data or I need to enhance my VBScript program. Please help to improve my VBScript below.
Thank you in advance.
Imports MySql.Data.MySqlClient
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim SQLConnectionSQL As MySqlConnection = New MySqlConnection
Dim connectionStringSQL As String = "Data Source=solomon;Initial Catalog=testapp;Persist Security Info=True;User ID=sa;Password=Passw0rd"
Dim connectionString As String = "Server=192.168.1.199; User Id=gil; Password=Passw0rd; Database=testapp"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Dim oDt_sched As New DataTable()
Private Sub btnRetrieve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRetrieve.Click
Dim con_Solomon As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
Dim str_carSql As String
lblCounter.Text = 0
con_Solomon = "Data Source=solomon;Initial Catalog=MARYLANDAPP;Persist Security Info=True;User ID=sa;Password=Passw0rd"
sql = "SELECT LTRIM(RTRIM(DocType)) as DocType, LTRIM(RTRIM(cust_classID)) as cust_classID, LTRIM(RTRIM(salesman)) as salesman, LTRIM(RTRIM(CustId)) as CustId, LTRIM(RTRIM(name)) as name, LTRIM(RTRIM(ClassID)) as ClassID, LTRIM(RTRIM(invoice_no)) AS refnbr, invoice_delv_date AS Delv_DocDate, Age, AR_Amount, LTRIM(RTRIM(STATUS)) as STATUS, LTRIM(RTRIM(AGE_GROUP)) as AGE_GROUP, LTRIM(RTRIM(company)) AS comp, '' AS Deposit_Date, Credit_Limit, LTRIM(RTRIM(Terms)) as Terms, LTRIM(RTRIM(customer_name)) AS ShipName, LTRIM(RTRIM(PO_Number)) as PO_Number, LTRIM(RTRIM(Kob)) as Kob, LTRIM(RTRIM(check_date)) as check_date FROM a_aging_ardoc_report"
connection = New SqlConnection(con_Solomon)
Try
connection.Open()
command = New SqlCommand(sql, connection)
command.CommandTimeout = 420
adapter.SelectCommand = command
adapter.Fill(ds, "PO_Monitoring")
adapter.Dispose()
command.Dispose()
connection.Close()
''****** MYSQL CONNECTION *****
SQLConnection = New MySqlConnection()
SQLConnection.ConnectionString = connectionString
SQLConnection.Open()
Dim sqlCommand As New MySqlCommand
Dim delv_docdate, check_date
For a = 0 To ds.Tables(0).Rows.Count - 1
With ds.Tables(0).Rows(a)
If Not IsDBNull(.Item(7)) Then
delv_docdate = .Item(7)
Else
delv_docdate = ""
End If
If Not IsDBNull(.Item(19)) Then
check_date = .Item(19)
Else
check_date = ""
End If
str_carSql = "insert into agingreportsummary(doctype,cust_classid,salesman,custId,name,classid,refnbr,delv_docdate,age,ar_amount,status,age_group,comp,credit_limit,terms,shipname,po_number,kob,check_date) " & _
"VALUES('" & .Item(0) & "','" & .Item(1) & "','" & Replace(.Item(2), "'", "") & "','" & .Item(3) & "','" & Replace(.Item(4), "'", "") & "','" & Replace(.Item(5), "'", "") & "','" & .Item(6) & "','" & delv_docdate & "'," & Replace(.Item(8), ",", "") & "," & Replace(.Item(9), ",", "") & ",'" & Replace(.Item(10), "'", "") & "','" & .Item(11) & "','" & .Item(12) & "','" & .Item(14) & "','" & .Item(15) & "','" & Replace(.Item(16), "'", "") & "','" & Replace(.Item(17), "'", "") & "','" & .Item(18) & "','" & check_date & "');"
End With
sqlCommand.Connection = SQLConnection
sqlCommand.CommandText = str_carSql
sqlCommand.ExecuteNonQuery()
Next a
SQLConnection.Close()
MsgBox("Finish")
Catch ex As Exception
MsgBox(str_carSql)
MsgBox(ex.Message)
End Try
End Sub
End Class
You can try using a parameterised query instead of building a query for each row. That should improve things slightly since the statement wouldn't need to be prepared every time.
Add all the required parameters to the command.
Set the command text once, and change it to use parameters.
Inside the loop you would only set the parameter values and call the executenonquery method
This would have the added benefit of not being vulnerable to sql injection.
Hope that helps

SQL parameterized? I'm lost

I have no idea how to use parameterized and would like someone to point me into the right direction.
Here's what I'm currently using.
Public Class main
Dim dbCon As New MySqlConnection("Server=localhost;Database=payid;Uid=root")
Dim strQuery As String = ""
Dim SQLCmd As MySqlCommand
Dim DR As MySqlDataReader
Private Sub Use()
Try
strQuery = "UPDATE payid " & _
"SET used='" & amen.Text & "' " & _
"WHERE payid='" & TextBox1.Text & "'"
SQLCmd = New MySqlCommand(strQuery, dbCon)
dbCon.Open()
SQLCmd.ExecuteNonQuery()
dbCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
If someone could change that for me I'd be able to do the rest of my code.
strQuery = "UPDATE payid SET used=#used WHERE payid=#payid "
SQLCmd = New MySqlCommand(strQuery, dbCon)
SQLCmd.Parameters.AddWithValue("#used", amen.Text)
SQLCmd.Parameters.AddWithValue("#payid", TextBox1.Text )