how to search and update record mysql in vb - mysql

i have problem to search and update record database sql.
this is my code. i using mysql database and Microsoft Visual Basic 2008
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim t As New Threading.Thread(AddressOf closeMsgbox)
objconn = New MySqlConnection("server=localhost;database=AAA;userid=root;password= 'root'")
Dim username As Boolean = True
objconn.Open()
Dim sqlquery As String = "SELECT * FROM daftar WHERE nid = '" & FormRegister.TextBox1.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = objconn
adapter.SelectCommand = command
data = command.ExecuteReader
If data.HasRows() = True Then
While data.Read()
FormRegister.Show()
tkhupd = Now.ToString("yyyy-MM-dd HH:mm:ss")
command.Connection = objconn
command.CommandText = "UPDATE visitor SET tkhupd ='" & tkhupd & "' WHERE nokp = '" & FormRegister.TextBox1.Text & "';"
command.ExecuteNonQuery()
MessageBox.Show("You're has logout")
FormRegister.TextBox1.Text = ""
username = False
Me.Close()
End While
Else
FormRegister.Show()
username = True
End If
data.Close()
If username = True Then
Dim sqlquery2 As String = "INSERT INTO visitor (nid)VALUES ('" & FormRegister.TextBox1.Text & "')"
Dim data2 As MySqlDataReader
Dim adapter2 As New MySqlDataAdapter
Dim command2 As New MySqlCommand
command2.CommandText = sqlquery2
command2.Connection = objconn
adapter2.SelectCommand = command2
data2 = command2.ExecuteReader
MessageBox.Show("You're has login")
Form4.Show()
FormRegister.TextBox1.Text = ""
Me.Close()
End If
End Sub
but i have error on Word command.ExecuteNonQuery(): MySqlException was unhandled. There is already an open DataReader associated with this Connection which must be closed first

You need to use a separate MySqlCommand object, say command2 inside your While statement , because command is already in active use:
Dim command2 As New MySqlCommand
..
While data.Read()
..
command2.Connection = objconn
..
End While

I would do this all in one call to the database, comprising two statements. I'm more used to Sql Server, so this syntax may be a little off, but it would look something like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlquery As String = _
"DECLARE #RowCount Int;" & _
" UPDATE FROM visitor v" & _
" INNER JOIN daftar d ON d.nid = v.nokp" & _
" SET v.tkhupd = current_timestamp" & _
" WHERE d.nid = ?NID;" & _
" SELECT row_count() INTO #RowCount;" & _
" IF #RowCount = 0 THEN " & vbCrLf & _
" INSERT INTO visitor (nid) VALUES (?NID);" & vbCrLf & _
" END IF"
Using conn As New MySqlConnection("server=localhost;database=AAA;userid=root;password= 'root'"), _
cmd As New MySqlCommand(sqlquery, conn)
cmd.Parameters.Add("?NID", MySqlDbTypes.Int).Value = Integer.Parse(FormRegister.TextBox1.Text)
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

Related

I'm inputing data in a db using mysqlcommand, but some variables are identified e other are not, check the code

My code:
Private Sub btnEnviartranche_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnviartranche.Click
Try
connection.Close()
connection.Dispose()
connection.Open()
Dim busca As New MySqlCommand("SELECT MAX(cod_tranche) +1 As id_last_tranche FROM long_short_tranche", connection)
Dim adapter As New MySqlDataAdapter(busca)
Dim table As New DataTable()
adapter.Fill(table)
Dim retorno = busca.ExecuteReader
Dim id_ultima_tranche = ""
Dim tipo_operacao As String = dg_ctrlv.Rows(1).Cells(0).Value.ToString
Dim ativo As String = dg_ctrlv.Rows(2).Cells(2).Value.ToString
Dim quantidade As String = dg_ctrlv.Rows(2).Cells(3).Value.ToString
Dim preco_executado As String = dg_ctrlv.Rows(2).Cells(4).Value.ToString
If retorno.Read() Then
id_ultima_tranche = retorno.GetString(0)
End If
connection.Close()
connection.Dispose()
connection.Open()
Dim nova_tranche = id_ultima_tranche + 1
Dim hora = DateTime.Now
' ======= The error happens on the line below ========
Dim query As New MySqlCommand("INSERT INTO long_short_tranche (cod_tranche, cod_cliente, nocional, title_operation, tipo_operacao, ativo, quantidade, preco_executado, data_hora) SELECT ('" & nova_tranche & "', cod_cliente, nocional, title_operation,'" & hora & "','" & tipo_operacao & "','" & ativo & "','" & quantidade & "','" & preco_executado & "') FROM long_short WHERE title_operation = '" & cbox_operacao.Text & "' AND confirmacao = 'Sim' AND flg_visualizar = 1 ", connection)
Dim adapter2 As New MySqlDataAdapter(query)
Dim table2 As New DataTable()
adapter2.Fill(table2)
Dim retorno2 = query.ExecuteReader
MessageBox.Show("Dados atualizados com sucesso!")
Catch ex As Exception
MessageBox.Show("Erro ao consultar tabela!")
End Try
End Sub
This is what happens
This is crazy-vulnerable to sql injection. NEVER use string concatenation like that to put values into a query! It's very likely the problem is a stray apostrophe somewhere in the data, and proper SQL coding practice would have avoided this, while also fixing the MASSIVE security issue.
Try it like this:
Dim sql As String = "
INSERT INTO long_short_tranche
(cod_tranche, cod_cliente, nocional, title_operation, tipo_operacao, ativo, quantidade, preco_executado, data_hora)
SELECT #nova_tranche, cod_cliente, nocional, title_operation, #hora, #tipo_operacao, #ativo, #quantidade, #preco_executado
FROM long_short
WHERE title_operation = #operacao AND confirmacao = 'Sim' AND flg_visualizar = 1
"
Using connection As New MySqlConnection("connection string here")
Using query As New MySqlCommand(sql, connection)
query.Parameters.AddWithValue("#nova_tranche", nova_tranche)
query.Parameters.AddWithValue("#hora", hora)
query.Parameters.AddWithValue("#tipo_operacao", tipo_operacao)
query.Parameters.AddWithValue("#ativo", ativo)
query.Parameters.AddWithValue("#quantidade", quantidade)
query.Parameters.AddWithValue("#preco_executado", preco_executado)
query.Parameters.AddWithValue("#operacao", cbox_operacao.Text)
connection.Open()
query.ExecuteNonQuery() ' ...
End Using
End Using

INSERT INTO in MySQL not working but no errors?

I somehow can't insert data into my MySQL database but I know there's no trouble with the query cause there is no error message and it can make it as far as the Success message box. I think the query is right for MySQL but it is not the specific one that I should use for INSERT INTO.
Here's my code:
Imports MySql.Data.MySqlClient
Public Class Register
Dim ServerString As String = "Server=localhost; UserId =root; Password = ; Database = gym;"
Dim MysqlConn As MySqlConnection = New MySqlConnection
Dim COMMAND As MySqlCommand
Dim password, pass As String
Dim member As Integer
Private Sub Register_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToParent()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MysqlConn.ConnectionString = ServerString
Dim READER As MySqlDataReader
password = TextBox2.Text
pass = TextBox3.Text
confirm(password, pass)
If TextBox1.Text = Nothing Or TextBox2.Text = Nothing Or TextBox3.Text = Nothing Or TextBox4.Text = Nothing Or TextBox5.Text = Nothing Or TextBox6.Text = Nothing Or DateTimePicker1.Text = Nothing Or RadioButton1.Checked = False And RadioButton2.Checked = False Then
MsgBox("Please Fill your Information Completely")
Else
MysqlConn.ConnectionString = ServerString
Try
MysqlConn.Open()
Dim query As String
query = "select * from gym.user where user_name ='" & TextBox1.Text & "'"
COMMAND = New MySqlCommand(query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
While READER.Read
count = count + 1
End While
MysqlConn.Close()
If count > 0 Then
MsgBox("User Already Exists")
Else
MysqlConn.Open()
query = "INSERT INTO gym.user(user_name,user_password,user_firstname,user_lastname,user_birthday,user_contact,user_membership) VALUES ('" & TextBox1.Text & "', md5('" & TextBox2.Text & "') ,'" & TextBox4.Text & "','" & TextBox5.Text & "','" & DateTimePicker1.Value.Date & "','" & TextBox6.Text & "','" & member & "')"
COMMAND = New MySqlCommand(query, MysqlConn)
MsgBox("USER REGISTERED")
MysqlConn.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End If
End Sub
You're missing ExecuteNonQuery statement:
query = "INSERT INTO gym.user(user_name,user_password,user_firstname,user_lastname,user_birthday,user_contact,user_membership) VALUES ('" & TextBox1.Text & "', md5('" & TextBox2.Text & "') ,'" & TextBox4.Text & "','" & TextBox5.Text & "','" & DateTimePicker1.Value.Date & "','" & TextBox6.Text & "','" & member & "')"
COMMAND = New MySqlCommand(query, MysqlConn)
COMMAND.ExecuteNonQuery()

Mysql server version for the riGht syntax to use near '",2016-01-13','2016-01-14')' at line 1

Private Sub btnIssue_Click (sender As System.Object, e As Syste.EventArgs) Handles btnIssue_Click
Try
Dim dbquery As String = "insert into tblIssued
values (" & cmbBookId.SelectedText & ",' " &
cmbIssueto.SelectedText & " ',' " &
txtIssuedDate.Text & " ',' " &
datepickerduedate.Text & " ' ) "
Dim dbConnection As New MysqlConnection(dbconstring)
Dim dbCmd As New MySqlCommand(dbquery,dbCOnnection)
Dim dbReader As MySqlDataReader
dbConnection.Open()
dbReader = dbCmd.ExecuteReader()
MsgBox("Issued")
You need to provide the column name as well like
insert into tblIssued(col1,col2,col3,col4)
values(value1,value2,value3,value4)
So in your case it would be like
Dim query As String = "insert into tblIssued(Bookid,Idno,Issuedate,Duedate)
values (#Bookid,#Idno,#Issuedate,#Duedate)"
Dim command As New SqlCommand(query, conn)
command.Parameters.Add("#Bookid", SqlDbType.Int).Value = Convert.toInt32(cmbBookId.SelectedText)
command.Parameters.Add("#Idno", SqlDbType.Int).Value = Convert.toInt32(cmbIssueto.Text)
command.Parameters.Add("#Issuedate", SqlDbType.DateTime).Value = txtIssuedDate.Text
command.Parameters.Add("#Duedate", SqlDbType.DateTime).Value = datepickerduedate.Text

How to get the value of a column and cell data?

I have a button "btnSetAppointment", I created a Scheduling system, and when I save an appointment it will automatically send a message to the patient's phone_number. However, I don't know how to get the value of phone_number from the table.
As you can see below, I declared number as string, I want to store the phone_number of a patient in the database.
Private Sub btnSetAppointment_Click(sender As Object, e As EventArgs) Handles btnSetAppointment.Click
'SMS
query = "SELECT * FROM schedule WHERE Phone_Number =" & frmViewSchedule.dgvSchedule.SelectedRows(3).Cells(0).Value
cmd = New MySqlCommand(query, MySqlConn)
reader = cmd.ExecuteReader
Dim number1 As String
If reader.HasRows Then
number1 = frmViewSchedule.dgvSchedule.SelectedRows(3).Cells(0).Value
With SerialPort1
.Write("at" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("at+cmgf=1" & vbCrLf)
Threading.Thread.Sleep(1000)
.Write("at+cmgs=" & Chr(34) & number1 & Chr(34) & vbCrLf)
.Write(sys_msg & Chr(26))
Threading.Thread.Sleep(1000)
MsgBox(rcvdata.ToString)
End With
End If
end sub
This is how I would do it using MySQL (after establishing a database connection).
Try
Dim MyDb As New Database_Connection
Dim query As String
query = "select phone_number from schedule where Phone_Number = '" & frmViewSchedule.dgvSchedule.SelectedRows(3).Cells(0).Value & "'"
Dim myReader As OdbcDataReader = MyDb.ExecuteQuery(query)
myReader.Read()
If reader.HasRows Then
dim ph_number as string = myReader.Item(0)
.
.
.
End if
myReader.Close()
MyDb.Dispose()
Catch ex As System.Data.Odbc.OdbcException
'MessageBox.Show(ex.ToString)
End Try

Select Value then Insert To Mysql

I'm trying to insert a value from a selected value. If the row fetched is equal to 1 or greater than 0 then It will insert the data to another table.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Try
con.Open()
sql = "SELECT user_id, username, password FROM tbl_user WHERE username = '" & txt_user.Text & "' AND password= '" & txt_pass.Text & "' IS NOT NULL"
cmd = New MySqlCommand(sql, con)
dr = cmd.ExecuteReader
While dr.Read
txt_user.Text = dr("username")
txt_pass.Text = dr("password")
Main.Show()
Me.Hide()
ctr += 1
End While
If ctr = 0 Then
MsgBox("Login Failed!")
txt_user.Clear()
txt_pass.Clear()
Else
sql = "INSERT INTO user_log(user_id, username, log_datetime)VALUES(" & dr(0) & ",'" & dr(1) & "','" & DateTime.Today & "')"
cmd2 = New MySqlCommand(sql, con)
cmd2.ExecuteNonQuery()
End If
dr.Close()
cmd.Dispose()
con.Close()
' Catch ex As Exception
' End Try
End Sub