I want to updating data at my database SQL with VB.NET. But I'm facing the problem.
For more specific, The data will updated when the Barcode Textbox is same as at Datagridview column. Here's my code
Private Sub nHarga_TextChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles nHarga.TextChanged
If cBarcode.Text <> "" Then
Dim isi As Integer
isi = Me.DataGridView1.CurrentRow.Index
With DataGridView1.Rows.Item(isi)
If .Cells(0).Value = cBarcode.Text Then
Try
Dim cmd As New MySqlCommand("update transaksi_sementara set jumlah = jumlah + 1 where barcode = '" & cBarcode.Text & "'", dbkon)
dbreader.Close()
If cmd.ExecuteNonQuery = 1 Then
Call bersih()
Call tampil()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
Else
Try
Dim cmd As New MySqlCommand("insert into transaksi_sementara values('" & cBarcode.Text & "','" & cNamaBarang.Text & "','1','" & nHarga.Text & "','" & nHarga.Text & "')", dbkon)
dbreader.Close()
If cmd.ExecuteNonQuery = 1 Then
Call bersih()
Call tampil()
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End If
End With
End If
End Sub
Related
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
I want to prevent duplicate entries to my inventory form using vb.net and MySQL as the database, here is my code:
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim myCommand As New MySqlCommand
Dim conn As MySqlConnection
Dim i As String
conn = New MySqlConnection
conn.ConnectionString = "server = localhost;username= root;password= a;database= secret"
Try
conn.Open()
Catch mali As MySqlException
MsgBox("connot establish connection")
End Try
Dim intReturn As Integer
Dim strSql As String = " select * from personnel where pcode = #pcode"
Dim sqlcmd As New MySqlCommand(strSql, conn)
With sqlcmd.Parameters
.AddWithValue("#pcode", CType(pcode.Text, String))
End With
intReturn = sqlcmd.ExecuteScalar
If (intReturn > 0) Then
cmd = New MySqlCommand("Insert into personnel values('" & pcode.Text & "','" & lname.Text & "','" & fname.Text & "','" & office.Text & "','" & designation.Text & "')")
i = cmd.ExecuteNonQuery
If pcode.Text <> "" Then
ElseIf i > 0 Then
MsgBox("Save Successfully!", MessageBoxIcon.Information, "Success")
mrClean()
ListView1.Tag = ""
Call objLocker(False)
Call LVWloader()
Call calldaw()
Else
MsgBox("Save Failed!", MessageBoxIcon.Error, "Error!")
End If
Else
MsgBox("Personnel ID Already Exist!", MessageBoxIcon.Error, "Error!")
End If
end sub
i found this while i search for answer, but when i tried to run it, it does not read the insert command but rather it goes directly to the msbox "Personnel ID Already Exist" even if theres no thesame Personnel ID.
can someone check why it does not read the insert please,
my Database tables values:
pcode = primary key
lname = longtext
fname = longtext
office = longtext
designation = longtext
any help will be much appreciated, thanks,
Sorry to say this is the wrong approach.
Databases have a built in system to prevent data being duplicated. That's through primary keys or unique key constraints. In your case, you have already created a primary key. So there is absolutely no need for you to do that SELECT COUNT(*) query.
Instead, just directly insert into the table and catch the integrity error when the pcode already exists.
Try
cmd = New MySqlCommand("Insert into personnel values('" & pcode.Text & "','" & lname.Text & "','" & fname.Text & "','" & office.Text & "','" & designation.Text & "')")
i = cmd.ExecuteNonQuery
If pcode.Text <> "" Then
ElseIf i > 0 Then
MsgBox("Save Successfully!", MessageBoxIcon.Information, "Success")
mrClean()
ListView1.Tag = ""
Call objLocker(False)
Call LVWloader()
Call calldaw()
Else
MsgBox("Save Failed!", MessageBoxIcon.Error, "Error!")
End If
Catch ex As MySqlException
MsgBox("Personnel ID Already Exist!", MessageBoxIcon.Error, "Error!")
End Try
Please also refer to the MySQL Manual Page PRIMARY KEY and UNIQUE Index Constraints
There should be the way you:
1) write a Trigger before Insert, and check if there is any similar row exist.
2) Put Unique Index on columns
found the answer, as what #e4c5 said, its a wrong approach, so I restructed my code and finally made it work, just want to share the answer maybe it will help others.
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim myCommand As New MySqlCommand
Dim conn As MySqlConnection
Dim i As String
conn = New MySqlConnection
conn.ConnectionString = "server = localhost;username= root;password= a;database= secret"
Try
conn.Open()
Catch mali As MySqlException
MsgBox("connot establish connection")
End Try
Dim retval As String
Select Button4.Tag
Case "ADD"
with myCommand
.Connection = conn
.CommandText = "Select pcode from personnel where pcode = '" & pcode.Text & "'"
retval = .ExecuteScalar
If retval Is Nothing Then
.CommandText = "Insert into personnel values ('" & pcode.Text & "','" & lname.Text & "','" & fname.Text & "','" & office.text & "','" & designation.Text & "')"
.ExecuteNonQuery()
Else
MsgBox("Personnel ID Already Exist!", MessageBoxIcon.Error, "Error")
End If
End With
End Sub
Hi i am having problems highlighting or making my selected date bold. Example when i add event to that date it should be bold so i will know that there are entries inside the date. But It's not working and i dont know what's wrong.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=jared;password=jared;database=database"
Dim reader As MySqlDataReader
Try
mydbcon.Open()
Dim Query As String
Query = "Insert into database.calendar (eventname,EventDate,Time,Description) Values ('" & TextBox2.Text & "','" & Form4.MonthCalendar1.SelectionRange.Start & "','" & ComboBox1.SelectedItem & "','" & TextBox1.Text & "')"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader
MessageBox.Show("Event Succesfully Saved")
mydbcon.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
mydbcon.Dispose()
Try
mydbcon.Open()
Dim eventdate As String
eventdate = "SELECT * FROM database.calendar Where EventDate = '" & Form4.MonthCalendar1.SelectionRange.Start & "'"
reader = COMMAND.ExecuteReader
If reader.HasRows = True Then
While reader.Read
eventdate = reader.GetValue(reader.GetOrdinal("EventDate")).ToShortDateString
Form4.MonthCalendar1.AddBoldedDate(CDate(eventdate))
End While
reader.Close()
Form4.MonthCalendar1.UpdateBoldedDates()
End If
mydbcon.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
mydbcon.Dispose()
End Try
End Try
End Sub
End Class
I have this datagridview whose rows are manually added on a click of a button.
What I wanted to do was to somehow loop through each row and insert it in a mysql database
here is my current code:
Public Sub addResBulk()
Dim cmdAddRes As New MySqlCommand
Dim addResQry As String
'field remarks left empty until process complete
With cmdAddRes
.Parameters.AddWithValue("#ctrlno", ctrlNo)
.Parameters.AddWithValue("#resdate", dtp_resDate.Value)
.Parameters.AddWithValue("#timestart", cbo_start.SelectedValue)
.Parameters.AddWithValue("#timeend", cbo_end.SelectedValue)
.Parameters.AddWithValue("#claimdate", claimdate)
.Parameters.AddWithValue("#borrowerid", tb_borrowerID.Text)
.Parameters.AddWithValue("#resloc", tb_location.Text)
End With
For row As Integer = 0 To dgv_bulk.Rows.Count - 1
Try
addResQry = "INSERT INTO tbl_test(ControlNo, bCode, Qty, resDate, timeSTART, timeEND, claimDate, borrowerID, resLocation) VALUES " _
+ "(#ctrlno, #bcode, #qty, #resdate, #timestart, #timeend, #claimdate, #borrowerID, #resloc)"
If conn.State = ConnectionState.Open Then
conn.Close()
conn.Open()
Else
conn.Open()
End If
'dgv_bulk.Item(1, o).Value
With cmdAddRes
.Parameters.AddWithValue("#bcode", dgv_bulk.Item(1, row).Value)
.Parameters.AddWithValue("#qty", dgv_bulk.Item(2, row).Value)
qryRes = .ExecuteNonQuery
End With
conn.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
Next row
End Sub
However, an error gets in the way of successfully inserting each row into the database.
it tells me that parameter #ctrlno is already defined. and another error telling me that i need a valid and open connection...
Any ideas?
Thanks in advance!
This will Also work
For x As Integer = 0 To yourdatagridviewname.Rows.Count - 1
Dim str1 = "INSERT INTO [expensesTB]([amount],[description],[expensesDate])values(#amount,#description,#expensesDate)"
Dim com As New OleDb.OleDbCommand(str1, con)
com.Parameters.AddWithValue("#amount", yourdatagridviewname.Rows(x).Cells(2).Value)
com.Parameters.AddWithValue("#description", yourdatagridviewname.Rows(x).Cells(1).Value)
com.Parameters.AddWithValue("#expensesDate", thisyear.ToString("yyyy/MM/dd"))
com.ExecuteNonQuery()
com.Dispose()
Next
Try this if you want to insert the data that you manually input in the Datagridview into Mysql database.
Hope this will help you.
Public Sub addResBulk()
''create connection
Dim conn As MySqlConnection = New MySqlConnection(connectionString)
conn.Open()
Dim comm As MySqlCommand = New MySqlCommand()
comm.Connection = conn
''insert data to sql database row by row
Dim ctrlno, bcode, resdate, timestart, timeend, claimdate, borrowerID, resloc As Object
Dim qty As Double
Dim tbl_test As New DataTable
For i = 0 To DataGridView1.Rows.Add - 1 Step 1
ctrlno = DataGridView1.Rows(i).Cells(0).Value()
bcode = DataGridView1.Rows(i).Cells(1).Value()
qty = DataGridView1.Rows(i).Cells(2).Value()
resdate = DataGridView1.Rows(i).Cells(3).Value()
timestart = DataGridView1.Rows(i).Cells(4).Value()
timeend= DataGridView1.Rows(i).Cells(5).Value()
claimdate = DataGridView1.Rows(i).Cells(6).Value()
borrowerID = DataGridView1.Rows(i).Cells(7).Value()
resloc = DataGridView1.Rows(i).Cells(8).Value()
comm.CommandText = "insert into tbl_test(ControlNo,bCode,Qty,resDate,timeSTART,timeEND,claimDate,borrowerID,resLocation ) values('" & ctrlno & "','" & bcode & "','" & qty & "','" & resdate & "','" & timestart & "','" & timeend & "','" & claimdate & "','" & borrowerID & "','" & resloc & "')"
comm.ExecuteNonQuery()
Next
conn.Close()
Me.Close()
End If
End Sub
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