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
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 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()
Quick one for you.
I'm using the following code to insert a record into two tables in my mysql db...
SQLConnection.ConnectionString = connectionstring
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
Dim SQLStatement As String = "INSERT INTO hosts(name, description, host, type, port, hostname) VALUES('" & txtname.Text & "','" & txtdescription.Text & "','" & txthost.Text & "','" & cmbtype.Text & "','" & txtport.Text & "','" & Pinger.resolvedstatus.Text & "'); SELECT LAST_INSERT_ID()"
SaveData(SQLStatement)
SQLConnection.Open()
SQLStatement = "INSERT INTO credentials(hosts_linked_id, username, password, type) VALUES('" & hosts_linked_id & "','" & txtusername.Text & "','" & txtpwd.Text & "','" & cmbtype.Text & "')"
SaveData(SQLStatement)
the Savedata() bit calls this function...
Public Sub SaveData(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
cmd.CommandText = SQLStatement
cmd.CommandType = CommandType.Text
cmd.Connection = SQLConnection
cmd.ExecuteNonQuery()
hosts_linked_id = CInt(cmd.ExecuteScalar())
SQLConnection.Close()
MsgBox("Host has been added - Host ID " & hosts_linked_id & "")
txtname.Text = ""
txtdescription.Text = ""
txthost.Text = ""
cmbtype.Text = ""
txtport.Text = ""
End Sub
The code is working in that the necessary records are inserted into both the 'hosts' and 'credentials' tables, however in each table the record is inserted twice.
obviously I don't want duplicate records in my db, so can anyone help me stop it from performing the insert twice?
Thanks in advance!!
You call it twice:
cmd.ExecuteNonQuery()
hosts_linked_id = CInt(cmd.ExecuteScalar())
Once as ExecuteNonQuery and second time as ExecuteScalar()
You need to remove one of them. Looking at the code, I guess maybe you need to introduce a parameter to SaveData method to say which one to use.
cmd.ExecuteNonQuery()
hosts_linked_id = CInt(cmd.ExecuteScalar())
Remove cmd.ExecuteNonQuery() To avoid Insert Twice
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 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