Select Value then Insert To Mysql - 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

Related

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()

prevent duplicate entries to database

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

MySQL Syntax Error in VB.NET

Here's the code of my button_click:
Private Sub Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button10.Click
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
conn.ConnectionString = "server = localhost; user id = root; database = db; password = root"
cmd.Connection = conn
conn.Open()
cmd.CommandText = " SELECT * FROM candidate WHERE idn = '" & TextBox4.Text & "'"
dr = cmd.ExecuteReader
If dr.HasRows Then
MessageBox.Show("Entry I.D. No. already exist", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
ElseIf TextBox4.Text = "" Or TextBox5.Text = "" Or TextBox6.Text = "" Or TextBox7.Text = "" Or ComboBox1.Text = "" Or TextBox3.Text = "" Then
MessageBox.Show("Please complete the required fields..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
conn.Close()
con.ConnectionString = "server = localhost; user id = root; database = db; password = root"
cmd.Connection = con
con.Open()
Dim sqlQuery As String = "INSERT INTO candidate(idn,cfname,cmname,clname,cyr,sec,vyear,votes,pword) VALUES('" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "','" & ComboBox1.Text & "','" & TextBox3.Text & "',CONCAT(YEAR(NOW()),'-',(YEAR(NOW()) + 1),'0','" & TextBox2.Text & "')"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = con
.ExecuteNonQuery()
End With
MsgBox("Record Inserted")
End If
End Sub
what's wrong with my INSERT query? I can't seem to find anything wrong here, but VB.NET says it has error in " at line 1?
"INSERT INTO candidate(vyear) VALUES(CONCAT(YEAR(NOW()),'-',(YEAR(NOW()) + 1))"
There is a unbalanced open parenthesis before the second YEAR. Need to remove it
"INSERT INTO candidate(vyear) VALUES( CONCAT(YEAR(NOW()),'-',YEAR(NOW()) + 1) )"
Looking at the updated code you really need to start to use parameterized queries
Using con = new MySqlConnection(......)
Using cmd = con.CreateCommand()
con.Open()
Dim sqlQuery As String = "INSERT INTO candidate " & _
"(idn,cfname,cmname,clname,cyr,sec,vyear,votes,pword) VALUES(" & _
"#idn, #cfname, #cmname, #clname, #cyr, #sec, " & _
"CONCAT(YEAR(NOW()),'-',YEAR(NOW()) + 1), " & _
"#votes, #pword"
With cmd
.CommandText = sqlQuery
' is idn an integer field, then pass it as integer.
' instead if it is an autoincrement then remove it and let the db calculate for you
.Parameters.AddWithValue("#idn", Convert.ToInt32(TextBox4.Text))
.Parameters.AddWithValue("#cfname, TextBox5.Text)
.... and so on for every placeholder in the parameterized text above
.ExecuteNonQuery()
End With
MsgBox("Record Inserted")
End Using
End Using

How to fix when I'm editing a data in datagridview in another form all the content is being cleared?

Private Sub btnAddNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
'Try
If Not IsNumeric(txtUnit.Text) Then
MsgBox("Enter Unit Number.", MsgBoxStyle.Critical, "LASAC")
Exit Sub
ElseIf txtName.Text = "" Then
MsgBox("Enter Name.", MsgBoxStyle.Critical, "LASAC")
Exit Sub
End If
If DataGridView1.SelectedRows.Count = 0 Then
conn.ConnectionString = constring
conn.Open()
sSQL = "INSERT INTO tblBilling(Unit,FullName) VALUES(" & CInt(txtUnit.Text) & ",'" & Replace(txtName.Text, "'", "''") & "')"
cmd = New OleDbCommand(sSQL, conn)
cmd.ExecuteReader()
conn.Close()
MsgBox("Sucessfully added", MsgBoxStyle.Information, "New")
NewBtn.PerformClick()
Else
conn.ConnectionString = constring
conn.Open()
sSQL = "UPDATE tblBilling SET FullName = '" & Replace(txtName.Text, "'", "''") & "', Unit = " & CInt(txtUnit.Text) & " WHERE 'ID = '" & DataGridView1.SelectedRows(0).Cells(0).Value & ""
cmd = New OleDbCommand(sSQL, conn)
cmd.ExecuteReader()
conn.Close()
MsgBox("Successfully Updated", MsgBoxStyle.Information, "Update")
End If
DataGridView1.Rows.Clear()
showmember()
txtName.Enabled = False
txtUnit.Enabled = False
'Catch ex As Exception
' MsgBox(ex.Message, MsgBoxStyle.Critical, "Save")
'End Try
End Sub
Private Sub NewBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewBtn.Click
txtName.clear()
txtUnit.Clear()
txtUnit.Enabled = True
txtName.Enabled = True
DataGridView1.ClearSelection()
End Sub
Private Sub DeleteBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteBtn.Click
If DataGridView1.SelectedRows.Count <> 0 Then
If MsgBox("You are deleting a confidential data?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Statement Deleting") = MsgBoxResult.Yes Then
conn.ConnectionString = constring
conn.Open()
'MsgBox(DataGridView1.SelectedRows(0).Cells(0).Value)
sSQL = "DELETE FROM tblBilling WHERE ID = " & DataGridView1.SelectedRows(0).Cells(0).Value & ""
cmd = New OleDbCommand(sSQL, conn)
cmd.ExecuteReader()
conn.Close()
'MsgBox("Data successfully delete", MsgBoxStyle.Information, "DELETE")
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
NewBtn.PerformClick()
'Else
' MsgBox("Delete Canceled")
End If
End If
showmember()
txtName.Enabled = False
txtUnit.Enabled = False
End Sub
You have a code to clear all your rows, but didn't to retrieve the data bank
Else
conn.ConnectionString = constring
conn.Open()
sSQL = "UPDATE tblBilling SET FullName = '" & Replace(txtName.Text, "'", "''") & "', Unit = " & CInt(txtUnit.Text) & " WHERE 'ID = '" & DataGridView1.SelectedRows(0).Cells(0).Value & ""
cmd = New OleDbCommand(sSQL, conn)
cmd.ExecuteReader()
conn.Close()
MsgBox("Successfully Updated", MsgBoxStyle.Information, "Update")
End If
' you have clear all your rows here
DataGridView1.Rows.Clear()
showmember()
txtName.Enabled = False
txtUnit.Enabled = False
'Catch ex As Exception
' MsgBox(ex.Message, MsgBoxStyle.Critical, "Save")
'End Try

how to search and update record mysql in vb

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