I'm trying to insert data in MYSQL and get the latest ID but the problem is I'm Inserting Duplicate data
Is my syntax is wrong or something?
connection.Open()
insertString = "INSERT INTO `daily_report`(`saan_nalaman`,`purpose`, `usual_time`, `apps`,`feedback`,`userid`, `survey_at_what_blh`) VALUES ('" & txtq1.Text & "', '" & txtq2.Text & "', '" & txtq3.Text & "', '" & txtq4.Text & "', '" & txtq5.Text & "', '" & Utilities.UserID & "', '" & Login.RichTextBox1.Text & "');SELECT last_insert_id();"
command = New MySqlCommand(insertString, connection)
reader = command.ExecuteReader
connection.Close()
connection.Open()
TextBox1.Text = command.ExecuteScalar
connection.Close()
Declare and dispose your database objects in the method where they are used. Using blocks handle this for us even if there is an error. Always use parameters to avoid sql injection. Also, it makes the sql command easier to read and write without all the concatenation and single quotes. A single ExecuteScalar will accomplish both the insert and the select.
Private ConStr As String = "Your connection string"
Private Sub GetID()
Dim insertString = "INSERT INTO `daily_report`(`saan_nalaman`,`purpose`, `usual_time`, `apps`,`feedback`,`userid`, `survey_at_what_blh`) VALUES (#saan, #purpose, #time, #apps, #feedback, #userid, #survey) SELECT last_insert_id();"
Dim id As Integer
Using Command As New MySqlCommand(insertString, New MySqlConnection(ConStr))
With Command.Parameters
.AddWithValue("#saan", txtq1.Text)
.AddWithValue("#purpose", txtq2.Text)
.AddWithValue("#time", txtq3.Text)
.AddWithValue("#apps", txtq4.Text)
.AddWithValue("#feedback", txtq5.Text)
.AddWithValue("#userid", Utilities.UserID)
.AddWithValue("#survey", Login.RichTextBox1.Text)
End With
Command.Connection.Open()
id = CInt(Command.ExecuteScalar)
End Using
TextBox1.Text = id.ToString
End Sub
Related
Error message - ('Incorrect date value: '11/17/2021' for column 'Date_joined' at row1)
Dim query As String
conn.Open()
query = "INSERT INTO `librarydb`.`tblmember` (`Name`, `NIC`, `Gender`,`Contact`,`Email`,`Date_Joined`) VALUES ('" & txtname.Text & "', '" & txtNIC.Text & "', '" & txtgender.Text & "','" & txtcontact.Text & "','" & txtemail.Text & "','" & DateTimePicker1.Value.Date & "');"
COMMAND = New MySqlCommand(query, conn)
RENDER = Command.ExecuteReader
Never concatenate strings to build a CommandText. ALWAYS use parameters. A value inserted in a text box and concatenated into CommandText can be executed by the server. (Drop Table) Values of parameters are not considered as executable code by the server.
You wouldn't open the connection until directly before the Execute....
You would use ExecuteReader with an Insert command.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim query = "INSERT INTO `librarydb`.`tblmember` (`Name`, `NIC`, `Gender`,`Contact`,`Email`,`Date_Joined`)
VALUES (#Name, #NIC, #Gender, #Contact, #Email, #Date);"
Using conn As New MySqlConnection("Your connection string"),
cmd As New MySqlCommand(query, conn)
With cmd.Parameters
.Add("#Name", MySqlDbType.VarChar).Value = txtname.Text
.Add("#NIC", MySqlDbType.VarChar).Value = txtNIC.Text
.Add("#Gender", MySqlDbType.VarChar).Value = txtgender.Text
.Add("#Contact", MySqlDbType.VarChar).Value = txtcontact.Text
.Add("#Email", MySqlDbType.VarChar).Value = txtemail.Text
.Add("#Date", MySqlDbType.Date).Value = DateTimePicker1.Value.Date
End With
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
hi im trying to insert dates from vb.net into my sql database and the results keep showing as 00-00-00 i use a date time picker to get the date which is formated to short
Public Sub NewAppointment()
SQLCommand.Connection = SQLconnection
SQLCommand.CommandText = "INSERT INTO " & _
appointment(TattooID,Date,Time,Length,Deposit,Cost) VALUES"& _
('" & _Tattoo.ID & "','"& _
" & AppDate.Date & "','" & _
" & AppTime & "','" & _
" & AppLength.ToString & "','" & _
" & AppDespoit & "','" & AppCost & "');"
SQLCommand.CommandType = CommandType.TableDirect
Try
SQLconnection.Open()
SQLCommand.ExecuteNonQuery()
SQLconnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
SQLconnection.Dispose()
End Sub
As usual these problems (and other as well) are totally avoided with a parameterized query
This is an example, you need to fix the correct datatype (MySqlDbType) for each parameter to match the datatype of your datatable fields
SQLCommand.Connection = SQLconnection
SQLCommand.CommandText = "INSERT INTO " & _
" appointment(TattooID,Date,Time,Length,Deposit,Cost) VALUES "& _
" (#id, #appDate, #AppTime, #AppLength,#AppDespoit,#AppCost);"
SQLCommand.Parameters.Add("#id", MySqlDbType.VarChar).Value = _Tattoo.ID
SQLCommand.Parameters.Add("#AppDate", MySqlDbType.Date).Value = AppDate.Date
SQLCommand.Parameters.Add("#AppTime", MySqlDbType.Date).Value = AppTime
SQLCommand.Parameters.Add("#AppLength", MySqlDbType.VarChar).Value = AppLength
SQLCommand.Parameters.Add("#AppDespoit", MySqlDbType.VarChar).Value = AppDespoit
SQLCommand.Parameters.Add("#AppCost", MySqlDbType.VarChar).Value = AppCost
Now, the job to get a correct value for your date field is passed to the database engine that receives a parameter of type Date and knows how to extract the value from the parameter and store it in the relative field.
Notice how your query is now more readable and, as an added benefit, you avoid any possible Sql Injection
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()
I am trying to insert data to mysql from vb.net. When I use concatenated sql query, it works well but when I make it paramatized, no error is shown by the vb.net try and catch statement, but wrong values and some null values are sent.
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=127.0.0.1;userid=root;password=root;database=my_mysql_database"
Dim READER As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
'Query = "INSERT INTO my_mysql_database.edata(E_id,Name,Surname,Age,user_name,password, Gender)values('" & Txt_EID.Text & "', '" & Txt_Name.Text & "', '" & Txt_Surname.Text & "', '" & Txt_Age.Text & "', '" & Txt_User_Name.Text & "', '" & Txt_Password.Text & "', '" & Txt_Gender.Text & "')"'
Query = "INSERT INTO my_mysql_database.edata
values(E_id=#Eid, Name=#Name, Surname=#Surname, Age=#Age,
user_name=#UserName, password=#Pass, Gender=#Gender, DOB=#Dob,
Image=#Ima, Email=#Email)"
COMMAND = New MySqlCommand(Query, MysqlConn)
COMMAND.Parameters.AddWithValue("#Eid", Txt_EID.Text)
COMMAND.Parameters.AddWithValue("#Name", Txt_Name.Text)
COMMAND.Parameters.AddWithValue("#Surname", Txt_Surname.Text)
COMMAND.Parameters.AddWithValue("#Age", Txt_Age.Text)
COMMAND.Parameters.AddWithValue("#UserName", Txt_User_Name.Text)
COMMAND.Parameters.AddWithValue("#Pass", Txt_Password.Text)
COMMAND.Parameters.AddWithValue("#Gender", Txt_Gender.Text)
COMMAND.Parameters.AddWithValue("#Dob", DTP_Date.Value)
COMMAND.Parameters.AddWithValue("#Ima", Txt_Image.Text)
COMMAND.Parameters.AddWithValue("#Email", Txt_Email.Text)
READER = COMMAND.ExecuteReader
MsgBox("Added to Database")
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
When I do the paramatized way no error is shown, but a zero and all nulls are saved in mysql database.
During Debug I have checked the values stored in the parameters and they are correct, but what is sent to Mysql dataabse is a zero and all NULLS. What could be happening. How can Isend the correct values to Mysql Database
edit:
Here is a picture of datatypes
I might be off here, if that is the case someone can educate me. My SQL knowledge tells me your query is wrong.
You say that this one work:
Query = "INSERT INTO my_mysql_database.edata(E_id,Name,Surname,Age,user_name,password, Gender)values('" & Txt_EID.Text & "', '" & Txt_Name.Text & "', '" & Txt_Surname.Text & "', '" & Txt_Age.Text & "', '" & Txt_User_Name.Text & "', '" & Txt_Password.Text & "', '" & Txt_Gender.Text & "')"'
So why change the format of the second query? INSERT INTO Table Values (Column=Value)
Surely it is supposed to be INSERT INTO Table (Column) Values (Value). Hence your query should look like this:
Query = "INSERT INTO my_mysql_database.edata (E_id,Name,Surname,Age,user_name,password,Gender,DOB,Image,Email) Values (#Eid,#Name,#Surname,#Age,#UserName,#Pass,#Gender,#Dob,#Ima,#Email)
Also, I strongly suggest you setup E_id to be auto incremental. Adding the ID yourself seems a bit unecessary.
Hoping someone can help me out with this.
I've made an app linked to a mysql db.
I'm writing details of remote hosts to a database at the minute.
I'm saving remote credentials too, but in a different table.
I have a colomn in my 'credentials' table called 'hosts_linked_id' which i want to contain the id of the parent record in the 'hosts' table.
Here is my code so far...
SQLConnection.ConnectionString = connectionstring
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
Dim SQLStatement As String = "INSERT INTO hosts(name, description, host, type, port) VALUES('" & txtname.Text & "','" & txtdescription.Text & "','" & txthost.Text & "','" & cmbtype.Text & "','" & txtport.Text & "')"
SaveData(SQLStatement)
SQLConnection.Open()
SQLStatement = "INSERT INTO credentials(hosts_linked_id, username, password, type) VALUES('" & txtname.Text & "','" & txtusername.Text & "','" & encryptedpassword & "','" & cmbtype.Text & "')"
SaveData(SQLStatement)
Else
SQLConnection.Close()
End If
Also, here's the 'SaveData' function...
Public Sub SaveData(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
SQLConnection.Close()
MsgBox("Host has been added")
txtname.Text = ""
txtdescription.Text = ""
txthost.Text = ""
cmbtype.Text = ""
txtport.Text = ""
End Sub
What i need to do is get the id of the record created when my first 'INSERT' statement is executed into a variable so i can insert it into the 'credentials' table when my second 'INSERT' statement is executed.
I've googled the hell out of this and tried a few different methods, all without success.
Can anyone help point me in the right direction?
Thanks in advance!!
TL;DR: Need to get the ID of mysql record added when insert statement is executed and drop it into a variable