mysql to vb.net command - mysql

please help me on this code
when i run this code i having a error " invalid attempt to read when reader is close"
q = "select * from test.table1"
com = New MySqlCommand(q, con)
rs = com.ExecuteReader
While rs.Read
Dim ln = rs.GetInt64("id1")
Dim fn = rs.GetString("name")
If fn = TextBox1.Text Then
rs.Close()<this line having error>
f1 = "INSERT INTO test.table2(id2,fname,Mname,name)VALUE('" & "null" & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & Val(ln) & "')"
com = New MySqlCommand(f1, con)
com.ExecuteNonQuery()
End If
End While
con.Close()
rs.Dispose()
MsgBox("successfully inserted the data")

If you enter the if block you close the MySqlDataReader because you need to run an insert command, but when a connection is busy serving a DataReader cannot be used to serve another command. However the code continues and the next loop is executed. At this point if you try to read using the previous variable you get the error because the MySqlReader has been closed at the previous loop.
You could fix the problem opening a second connection using the connectionstring from the first connection. This seems to be the required path with MySql .NET Adapter because it doesn't support the MultipleActiveResultSets keyword in the connection string like SqlServer
While rs.Read
Dim ln = rs.GetInt64("id1")
Dim fn = rs.GetString("name")
If fn = TextBox1.Text Then
f1 = "INSERT INTO ........"
Using con2 = new MySqlConnection(con.ConnectionString)
con2.Open()
com = New MySqlCommand(f1, con2)
com.ExecuteNonQuery()
End Using
End If
End While

Related

cannot insert path file address to mysql using vb.net

i have problem to insert this text to mysql in vb.net
C:\Users\Riski\Documents\Visual Studio 2012\Projects\Remainder\Remainder\images\activ\
and this my source for insert
Try
Dim tbimg As String
tbimg = tbimgpath.text
'Prepare Connection and Query
dbconn = New MySqlConnection("Server=localhost;Database=team;Uid=root;Pwd=")
'OPEN THE DB AND KICKOFF THE QUERY
dbconn.Open()
DS = New DataSet
DA = New MySqlDataAdapter("INSERT INTO tb_team_user (id_team_user,user_ip,user_team,user_image_path) values (null,'" & lip.Text & "','" & tbteam.Text & "','" & tbimg & "')", dbconn)
DA.Fill(DS, "tb_info_activity")
'DONE CLOSE THE DB
dbconn.Close()
Application.Restart()
Catch ex As Exception
MsgBox("cannot connect to database!" & vbCrLf & vbCrLf & ex.Message)
End Try
if i write without symbol '\' and ':' the insert work fine but if i write with symbol and the insert give me warning just "check the manual that corresponds"
how resolve this?
thanks
Don't use string concatenation to build your sql query. Otherwise you are open for sql injection and other issues like this. The backslash introduces escape characters like \r for carriage return. So just use sql-parameters with the correct types:
Using dbconn = New MySqlConnection("connectionstring")
Dim insertSql = "INSERT INTO tb_team_user (id_team_user,user_ip,user_team,user_image_path)" & _
"VALUES (null,#user_ip,#user_team,#user_image_path)"
Using da As New MySqlDataAdapter()
da.InsertCommand = New MySqlCommand(insertSql, dbconn)
da.InsertCommand.Parameters.Add("#user_ip", MySqlDbType.Int32).Value = Int32.Parse(lip.Text)
da.InsertCommand.Parameters.Add("#user_team", MySqlDbType.VarChar).Value = tbteam.Text
da.InsertCommand.Parameters.Add("#user_image_path", MySqlDbType.VarChar).Value = tbimg.Text
' .. '
End Using
End Using
Apart from that, why do you use an INSERT-sql for DataAdaper.Fill? You need a Select.
So maybe you want to use MySqlCommand.ExecuteNonQuery instead:
Using dbconn = New MySqlConnection("connectionstring")
Dim insertSql = "INSERT INTO tb_team_user (id_team_user,user_ip,user_team,user_image_path)" & _
"VALUES (null,#user_ip,#user_team,#user_image_path)"
Using cmd As New MySqlCommand(insertSql, dbconn)
cmd.Parameters.Add("#user_ip", MySqlDbType.Int32).Value = Int32.Parse(lip.Text)
cmd.Parameters.Add("#user_team", MySqlDbType.VarChar).Value = tbteam.Text
cmd.Parameters.Add("#user_image_path", MySqlDbType.VarChar).Value = tbimg.Text
dbconn.Open()
Dim insertedCount As Int32 = cmd.ExecuteNonQuery()
End Using
End Using

Open DataReader associated with this Connection which must be closed first

I am trying to make a POS (Point of Sales) Application and I got this error. "There is already an open DataReader associated with this Connection which must be closed first."
Below are my codes:
Database using MySQL
If txt_notr.Text = "" Or txt_kodep.Text = "" Or txt_item.Text = "" Or txt_gt.Text = "" Or txt_bayar.Text = "" Then
MsgBox("Data belum lengkap...!!!")
Exit Sub
Else
'Simpan ke tabel penjualan
db.Close()
db.Open()
Call Koneksi()
Dim simpan1 As String = "Insert Into tb_penjualan values('" & txt_notr.Text & "','" & Format(Now, "yyyy-MM-dd") & "','" & txt_kodep.Text & "','" & txt_item.Text & "','" & txt_gt.Text & "','" & txt_bayar.Text & "')"
cmd = New MySqlCommand(simpan1, db)
cmd.ExecuteNonQuery()
db.Close()
db.Open()
'Simpan ke tabel detail penjualan
For baris As Integer = 0 To DGV.Rows.Count - 2
Dim simpandet As String = "Insert into tb_detjual values('" & txt_notr.Text & "','" & DGV.Rows(baris).Cells(0).Value & "','" & DGV.Rows(baris).Cells(3).Value & "','" & DGV.Rows(baris).Cells(4).Value & "','" & DGV.Rows(baris).Cells(5).Value & "')"
cmd = New MySqlCommand(simpandet, db)
cmd.ExecuteNonQuery()
db.Close()
db.Open()
cmd = New MySqlCommand("Select * from tb_stok where id_obat = '" & DGV.Rows(baris).Cells(0).Value & "'", db)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows Then
Dim kurangstok As String = "Update tb_stok set stok = '" & dr.Item("stok") - DGV.Rows(baris).Cells(4).Value & "' where id_obat = '" & DGV.Rows(baris).Cells(0).Value & "'"
cmd = New MySqlCommand(kurangstok, db)
cmd.ExecuteNonQuery() 'The Error shows here...
End If
Next
Call hapustemp()
Call bersih()
Call notrans()
End If
db.Close()
It's counter-intuitive, but ADO.Net providers use a feature called Connection Pooling, such that you really are better off creating a new connection object in most cases for individual calls to a database, rather than trying to keep a single database connection in your class to re-use. The code below shows the correct way to re-use the connection object: create a new connection for the method, and use it for the duration of the method. But then let the connection be collected when the method completes.
I noticed that you also have some seriously insecure code. Before doing any more work with databases, you should read up on Sql Injection. This is a HUGE issue. You should not be writing database code professionally if you don't know about it, and the correct way to avoid the problem.
Finally, the code uses some conventions that originated with older VBScript/VB6 and are no longer appropriate.
The code below solves all of those issues, and should be much faster by avoiding the need to run a SELECT from the database for each gridview row:
If String.IsNullOrWhiteSpace(txt_notr.Text) OrElse String.IsNullOrWhiteSpace(txt_kodep.Text) OrElse String.IsNullOrWhiteSpace(txt_item.Text) OrElse String.IsNullOrWhiteSpace(txt_gt.Text) OrElse String.IsNullOrWhiteSpace(txt_bayar.Text_ Then
MsgBox("Data belum lengkap...!!!")
Exit Sub
End If
'No need for an "Else". The "Exit Sub" takes care of it.
'Simpan ke tabel penjualan
'Note that I was able to let the database set the time stamp
Dim sql As String = "Insert Into tb_penjualan values(#notr, current_timestamp, #kodep, #item, #gt, #bayar);"
'The "Using" keyword will guarantee the connection closes, even if an exception is thrown
Using cn As New MySqlConnection(" connection string here "), _
cmd As New MySqlCommand(sql, cn)
'Use parameter placeholders rather than string concatenation. This avoids a SERIOUS security issue.
' I have to guess parameter types/lengths, but you should use actual types/lengths that match your database
cmd.Parameters.Add("#notr", MySqlDbType.Int32).Value = CInt(txt_notr.Text)
cmd.Parameters.Add("#kodep", MySqlDbType.VarChar, 20).Value = txt_kodep.Text
cmd.Parameters.Add("#item", MySqlDbType.VarString, 1000).Value = txt_item.Text
cmd.Parameters.Add("#gt", MySqlDbType.VarChar, 50).Value = txt_gt.Text
cmd.Parameters.Add("#bayar", MySqlDbType.VarChar, 50).Value = txt_bayar.Text
cn.Open()
cmd.ExecuteNonQuery()
'Two sql statements in a single call to the database.
'This is MUCH better than the Insert/Select/Update process you were using
sql = "INSERT INTO tb_detjual VALUES (#notr, #c0, #c3, #c4, #c5);" & _
"UPDATE tb_stok SET stok = stok - #c4 WHERE id_obat = #c0;"
'See how I was able to re-use the same parameters in the query.
cmd.Parameters.Clear()
cmd.CommandText = sql
cmd.Parameters.Add("#notr", MySqlDbType.Int32).Value = CInt(txt_notr.Text)
cmd.Parameters.Add("#c0", MySqlDbType.VarChar, 50)
cmd.Parameters.Add("#c3", MySqlDbType.VarChar, 50)
cmd.Parameters.Add("#c4", MySqlDbType.VarChar, 50)
cmd.Parameters.Add("#c5", MySqlDbType.VarChar, 50)
'Simpan ke tabel detail penjualan
For baris As Integer = 0 To DGV.Rows.Count - 2
'I'm able to re-use the same parameters for each loop
cmd.Parameters("#c0").Value = DGV.Rows(baris).Cells(0).Value
cmd.Parameters("#c3").Value = DGV.Rows(baris).Cells(3).Value
cmd.Parameters("#c4").Value = DGV.Rows(baris).Cells(4).Value
cmd.Parameters("#c5").Value = DGV.Rows(baris).Cells(5).Value
cmd.ExecuteNonQuery()
Next
End Using
hapustemp()
bersih()
notrans()

How do you insert a binary reader to string query for mysql?

I'm learning how to upload images into MySql database. Before you all get cranky and tell me that it's bad practice to upload images into mysql database, I AGREE WITH YOU, but it's for a school project and that's what the school wants.
This is what I found on the net and it works. But I would like to understand it more and maybe modify it to fit my custom subs. Also the datatype for the images is blob
Dim strFileName as String 'This is the file path
Dim con As MySqlConnection = New MySqlConnection(cnn.ConnectionString)
Dim cmd As MySqlCommand
Dim fs As FileStream
Dim br As BinaryReader
Dim FileName As String = strFileName.ToString
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()
If File.Exists(strFileName) = False Then MsgBox("Cannot locate file") : Return
Dim CmdString As String = "INSERT into tbl_maps(map_name,map_floor,map) Values('" & txtMapName.Text & "','" & cmbMapsFloor.Text & "',#Image)"
cmd = New MySqlCommand(CmdString, con)
cmd.Parameters.AddWithValue("Image", ImageData)
con.Open()
Now my question is, is there a way to insert ImageData into a string for the MySqlCommand? This is how I usually insert data into the database.
Public Sub RunQuery()
On Error Resume Next
dr.Close()
InitQuery()
cmd.ExecuteNonQuery()
End Sub
Public Sub InitQuery()
With cmd
.CommandText = sql
.Connection = cnn
End With
End Sub
Private Sub something()
sql = "INSERT into tbl_maps(map_name,map_floor) Values('" & txtMapName.Text & "','" & cmbMapsFloor.Text & "')"
RunQuery()
MsgBox("Data saved successfully") 'or some way to check the data inserted
End Sub
I was hoping for something that would maybe look like this
sql = "INSERT into tbl_maps(map_name,map_floor,map) Values('" & txtMapName.Text & "','" & cmbMapsFloor.Text & "','" & ImageData & "')"
RunQuery()
But I know that's not correct because sql is a string and ImageData is not. I'm just looking for a way to avoid using cmd.Parameters.AddWithValue("Image", ImageData) or at the very least integrate it into my RunQuery sub.
P.S.: Not that it really matters but I like 1 line code sets. Because I read lines like I read sentences. Example:
If RecordNotExist() = true then Msgbox("Record not found") : txtsearch.selectall() : txtsearch.focus() : return
Translation: If no records match the search query, search for something else.

Why do I keep getting this mysql error?

Hi stackoverflow people!
I have been recently developing a simple vb.net program that connects to a mysql database to register and login users with given credentials. I have used this code to register my users but I keep getting and error (below the code)
Dim insertUser As String = "INSERT INTO users(ID, username, password, email, verif)" _
& " VALUES('','" & Username.Text & "','" & Password.Text & "','" & Email.Text & "','" & currentRandString & "');"
Dim checkUsername As String = "SELECT * FROM users WHERE username='" & Username.Text & "'"
MysqlConn = New MySqlConnection()
MysqlConn.ConnectionString = mysqlconntxt4reg
MysqlConn.Open()
Dim myCommand As New MySqlCommand
myCommand.Connection = MysqlConn
myCommand.CommandText = checkUsername
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
If myData.HasRows > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
myData.Close()
Else
myData.Close()
Dim myCommand2 As New MySqlCommand
myCommand2.Connection = MysqlConn
myCommand2.CommandText = insertUser
myAdapter.SelectCommand = myCommand2
Dim myData2 As MySqlDataReader
myData2 = myCommand2.ExecuteReader
Mail(Email.Text, currentRandString)
Me.Close()
myData2.Close()
End If
Catch myerror As MySqlException
MsgBox("Error While Connecting To Database:" & vbNewLine & vbNewLine & myerror.ToString, MsgBoxStyle.Critical, "Error")
Finally
MysqlConn.Dispose()
End Try
I have closed all my datareaders before opening other ones so I do not see why this does not work...
Error:
Link to Error Image
I would appreciate any help on this topic!
Thanks
Rodit
I would use the using statement around all the disposable objects to be sure that they release every references to the connection when they are no more needed, but looking at your code, I think you don't need at all the datareaders because you could resolve your problem just with the commands
Dim insertUser As String = "INSERT INTO users(username, password, email, verif)" _
& " VALUES(#p1, #p2,#p3,#p4)"
Dim checkUsername As String = "SELECT COUNT(*) FROM users WHERE username=#p1"
Using MysqlConn = New MySqlConnection(mysqlconntxt4reg)
Using myCommand = New MySqlCommand(checkUsername, MysqlConn)
MysqlConn.Open()
myCommand.Parameters.AddWithValue("#p1", Username.Text)
Dim result = myCommand.ExecuteScalar()
if result IsNot Nothing AndAlso Convert.ToInt32(result) > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
Else
Using myCommand2 = New MySqlCommand(insertUser, MysqlConn)
mycommand2.Parameters.AddWithValue("#p1",Username.Text)
mycommand2.Parameters.AddWithValue("#p2",Password.Text )
mycommand2.Parameters.AddWithValue("#p3",Email.Text)
mycommand2.Parameters.AddWithValue("#p4",currentRandString )
myCommand2.ExecuteNonQuery()
Mail(Email.Text, currentRandString)
End Using
End If
End Using
End Using
Of course I have replaced your string concatenations with a parameterized query. This is really an important thing to do to avoid Sql Injection
I have replaced the query that checks the user existence with a scalar operation that can be used with the command ExecuteScalar. Also, in the first query, it seems that you try to insert the field ID with an empty string. I think that the first field (ID) is an autonumber field and, in this case, you don't add it to the insert query and don't pass any value because the database will calculate that field for you.

The connection property has not been set or is null

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.