Regarding to last_insert_id not working please help me - mysql

Here is what I have...
The problem is that last_insert_id not working
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
CMD.CommandText = "INSERT product_tbl (stockno, product_desc, price, Unit) VALUES (#stockno, #catid, #compid, #desc, #price, #unit);SELECT LAST_INSERT_ID()"
CMD.Parameters.AddWithValue("#stockno", txtstockno.Text)
CMD.Parameters.AddWithValue("#desc", txtdesc.Text)
CMD.Parameters.AddWithValue("#price", txtprice.Text)
CMD.Parameters.AddWithValue("#Unit", txtUnit.Text)
Dim ProductID As Int32
Try
ProductID = (System.Convert.ToInt32(CMD.ExecuteScalar))
Catch ex As Exception
TR.Rollback()
CN.Close()
Throw ex
End Try
'the code above are working just fine but when it comes the second insert to
'inventory_tbl it doesn't work at all. am i missing something or did wrong?
CMD.CommandText = "INSERT invetory_tbl (productid, qty) VALUES(#productID, #qty)"
CMD.Parameters.Clear()
CMD.Parameters.AddWithValue("#orderID", ProductID)
' CMD.Parameters.AddWithValue("#qty", txtqty.Text)
Try
CMD.ExecuteNonQuery()
Catch ex As Exception
TR.Rollback()
Throw ex
End Try
TR.Commit()
CN.Close()

last_insert_id only works if you have auto-increment variable in your table...
What is the table structure you have? Same can be seen by executing command DESCRIBE myTable
Also see if this link helps you

Related

Query getting executed in MySQL but while debugging gets error in vb.net

I have one insert query in which I am trying to copy table1 data to table2. Now Query works fine when I directly execute in MySQL but when I tried to debug via VB.Net"
INSERT INTO newMedicinesOrders (`OrderID`,`medicineName`, `power`, `form`, `fQuantity`, `iQuantity`, `type`, `cost`, `prescriptionLink`, `userID`) SELECT `orderID`, `name`, `power`, `form`, `fQuantity`, `iQuantity`, `type`, `mrp`, `prescriptionLink`, `userID` from myCart WHERE userID = '1'
I get an error message that says
Unknown column 'orderID' in 'field list'
vb code
Try
Dim str1 As String = "INSERT INTO newMedicinesOrders (`OrderID`,`medicineName`, `power`, `form`, `fQuantity`, `iQuantity`, `type`, `cost`, `prescriptionLink`, `userID`) SELECT `orderID`, `name`, `power`, `form`, `fQuantity`, `iQuantity`, `type`, `mrp`, `prescriptionLink`, `userID` from myCart WHERE userID = '" + userid.Text + "'"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
con.Open()
str2 = command.ExecuteReader
con.Close()
Response.Write("<script language='javascript'>alert('Success.');</script>")
Catch ex As Exception
Response.Write(ex)
End Try
I believe your error comes from the fact that you are using SQLCommand.ExecuteReader()
From this description :
ExecuteReader used for getting the query results as a DataReader object. It is readonly forward only retrieval of records and it uses select command to read through the table from the first to the last.
ExecuteNonQuery used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.
According to MSDN, this is how you execute an INSERT, UPDATE or DELETE statement :
Public Sub CreateCommand(ByVal queryString As String, ByVal connectionString As String)
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
command.Connection.Open()
command.ExecuteNonQuery()
End Using
End Sub
However, I did not find information on what happens when you execute an INSERT command using ExecuteReader(), but I guess that's what happens...

ExecuteNonQuery not deleting when it has to delete large number of rows

I would like to go over all the tables in the database and delete all rows with particular id. When the number of rows are smaller, it works fine.
in a particular table the number of rows is 900000 and this doesn't work anymore.
Here is my current code:
Using connection = New MySqlConnection(connectionString)
Try
connection.open()
If listOfTables.Count > 0 Then
For Each table As String In listOfTables
Dim sqlc As String = "DELETE FROM " & dbConnection.DbName & "." & table & " WHERE id=" & cNumber& ";"
Dim command3 As New MySqlCommand(sqlc , connection)
command3.ExecuteNonQuery()
command3.Dispose()
Next
connection.close()
End If
Catch ex As Exception
End Try
End Using
Deleting 900000 rows in once from table is not a good idea. Why don't you write a stored procedure in MYSQL which do your work. You can Try creating stored procedure which deletes records in chunks of 1000 rows in the loop and do not stop until all the rows deleted.
Try out following pseudo code:
#counter = 0
LOOP
DELETE FROM Table_name
WHERE id BETWEEN #counter AND #counter +1000
AND "Your conditions"
SET #counter = #counter + 1000
sleep 2 -- Take a sleep before next
UNTIL end of table
It uses the id column as Primary-key with auto increment
I agree with the above answer about the stored procedure loop.
However, you never mentioned if you are getting an error/exception or if it just times out.
Perhaps you should:
Catch ex As Exception
MessageBox.Show(ex.Message)
connection.close()
End Try

SQL "successful" but not updating the database?

lblMessage says that it's registered, however when I check my database there's no record.
Below is my code:
Try
con = New MySqlConnection("Server=localhost;Database;Uid=root;Pwd=;")
Using cmd = New MySqlCommand("START TRANSACTION; INSERT INTO account_table(acc_user, acc_pass, acc_mail, acc_ques, acc_ans, acc_priv) VALUES( #p3, #p4, #p5, #p6, #p7, 'user'); SELECT LAST_INSERT_ID(acc_id) FROM account_table; INSERT INTO patient_table(acc_id, pat_fname, pat_lname) VALUES (LAST_INSERT_ID(), #p1, #p2); COMMIT;", con)
cmd.Parameters.AddWithValue("#p1", firstname.Value.ToString)
cmd.Parameters.AddWithValue("#p2", lastname.Value.ToString)
cmd.Parameters.AddWithValue("#p3", username.Value.ToString)
cmd.Parameters.AddWithValue("#p4", password.Value.ToString)
cmd.Parameters.AddWithValue("#p5", email.Value.ToString)
cmd.Parameters.AddWithValue("#p6", quest.Value.ToString)
cmd.Parameters.AddWithValue("#p7", answer.Value.ToString)
con.Open()
End Using
lblMessage.Text = "Registered!"
Catch ex As Exception
lblMessage.Text = "The username or email appears to be taken."
End Try
con.Close()
No error appears so I'm not quite sure what is wrong
You never executed the statement. You need:
con.Open()
cmd.ExecuteNonQuery()
con.Close()

Return Last ID (IDENTITY) On Insert row VB.NET MySQL

Dim insert_coupon_query As String = ("INSERT INTO qa_discountcoupons (id, status_code) VALUES (AUTO_INCREMENT_ID, 5)")
Dim cmd_query As New MySqlCommand(insert_coupon_query, objConn)
Dim cmd_result As Integer = CInt(cmd_query.ExecuteScalar())
I want to return the AUTO_INCREMENT value of the current insert, and show in a msgbox.
You can use an double Query and use the function LAST_INSERT_ID() After run your first query to get the last current query:
Dim insert_coupon_query As String = ("INSERT INTO qa_discountcoupons (status_code) VALUES (5); SELECT LAST_INSERT_ID()")
Dim cmd_query As New MySqlCommand(insert_coupon_query, objConn)
Dim cmd_result As Integer = CInt(cmd_query.ExecuteScalar())
MsgBox(cmd_result)
Bit late to the party but after
cmd_query.ExecuteScalar()
MsgBox(cmd_query.LastInsertedId)
Produces the last insert id.
You can fetch the AUTO_INCREMENT value for a table through a MySQL query and then show that in your MsgBox

VB.net adding parent and child records to MySQL db

I was asked to create a program that inserts records into one parent table and multiple child tables. My question is, how do I know what the PK is for the parent table, so that I may add it as a FK in the child? The PK for the parent is an auto number. As I stated in my title, I'm using VB.net, mySQL, through an ODBC connection. I have to do this through the code and cannot use stored procedures. Any suggestions?
thanks
my transaction looks like this:
Dim cmdText As String = "INSERT INTO candidate(first_name, last_name, phone1, phone2, email1, city, " _
& " state, country, zip,primary_contact_id ) VALUES (?,?, ?, ?,?,?, ?,?,?,?)"
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim SqlStatus As Integer
Dim trans As Odbc.OdbcTransaction = conn.BeginTransaction(IsolationLevel.ReadCommitted)
Dim cmd As OdbcCommand = New OdbcCommand(cmdText, conn, trans)
Try
cmd.Parameters.Clear()
cmd.CommandType = CommandType.Text 'The default is CommandType.Text
With cmd.Parameters
.Add("#first_name", OdbcType.VarChar).Value = fName
.Add("#last_name", OdbcType.VarChar).Value = lName
.Add("#phone1", OdbcType.VarChar).Value = phone
.Add("#phone2", OdbcType.VarChar).Value = mobilePhone
.Add("#email1", OdbcType.VarChar).Value = email
.Add("#city", OdbcType.VarChar).Value = city
.Add("#state", OdbcType.VarChar).Value = state
.Add("#country", OdbcType.VarChar).Value = country
.Add("#zip", OdbcType.VarChar).Value = zip
.Add("#primary_contact_id", OdbcType.Int).Value = getContactFK
End With
SqlStatus = cmd.ExecuteNonQuery
If Not SqlStatus = 0 Then
trans.Commit()
Me.Close()
Else
MsgBox("Not Updated")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
trans.Dispose()
End Try
I'm still working on the code, so not sure if it works just yet
jason
Take a look at How to Get the Unique ID for the Last Inserted Row
Since you're going through ODBC and cannot use a stored proc you will have to execute two SQL statements together (as a batch). First your insert and then SELECT LAST_INSERT_ID()
It should look something like:
INSERT INTO ... ;
SELECT LAST_INSERT_ID();
Since you're expecting a result you need to execute from your client code as a SELECT statement. And since this is a batch operation with an insert you should also consider using a transaction.
You can use
"; select last_insert_id()"
At the end of your insert for the parent table. And then use
Dim id as Integer = cint(command.ExecuteScalar())
To get the resulting key to use in the child inserts