SQL "successful" but not updating the database? - mysql

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

Related

not getting the insert data in mysql using visual basic

when try to insert a data on my database it always received a null value
here is my code,
query = "INSERT INTO tbl_Inventory (Asset_Code,Item_Name,Category,Location,Serial_No,Description,Date_Acquired,Date_Inventory,Remarks,Item_Status)" _
"VALUES (#assetcode , #itemname , #category, #location, #serialNo, #description, #dateacquired, #dateinventory, #remarks, #itemstatus)"
Dim cmd As New Odbc.OdbcCommand(query, conn)
cmd.Parameters.AddWithValue("#assetcode", varasset)
cmd.Parameters.AddWithValue("#itemname", txtItemName.Text)
cmd.Parameters.AddWithValue("#category", txtcategory.Text)
cmd.Parameters.AddWithValue("#location", txtLocation.Text)
cmd.Parameters.AddWithValue("#serialNo", txtSerialNo.Text)
cmd.Parameters.AddWithValue("#description", txtDescription.Text)
cmd.Parameters.AddWithValue("#dateacquired", txtDateAcquired.Text)
cmd.Parameters.AddWithValue("#dateinventory", txtdateInventory.Text)
cmd.Parameters.AddWithValue("#remarks", txtRemarks.Text)
cmd.Parameters.AddWithValue("#itemstatus", cmbstatus.SelectedText)
cmd.ExecuteNonQuery()

How to check only month and year in MySQL DateTime column in Vb.net

Im saving some calculated values in to database each month.Before saving, i want to check data is already available for this month and year. IF the same month exists, then user has to select another month or leaving without saving that. In Vb.net, im using DateTimepicker for selecting month and save that in DateTIme format in mysql. In that i want to check only month and year is existing.
Mysql:
1 2019-05-01 14:24:20 ProA 8.34 3.59
2 2019-05-01 14:24:20 ProB 9.21 5.54
Here record available for ProA for May2019 is available. So user cannot save for may 2019 again.
Dim selectedDate = DateTimePicker1.Value
Dim startDate = New Date(selectedDate.Year, selectedDate.Month, 1)
conn.Open()
sQuery = "SELECT * FROM riskanalysis WHERE DATE_FORMAT(reportdate,'%c %Y') >= #StartDate "
cmd_listview = New MySqlCommand(sQuery, conn)
cmd_listview.Parameters.AddWithValue("#StartDate", startDate)
Using reader As MySqlDataReader = cmd_listview.ExecuteReader()
If reader.HasRows Then
' User already exists
MsgBox("Record Already Exist for this Month!", MsgBoxStyle.Exclamation, "Select another month!")
Else
sQuery = "INSERT INTO riskanalysis (reportdate, process, avgrisk, avgriskafterImp) VALUES (#dat, #process, #avgrisk, #riskafterimp);"
For i As Integer = 0 To ProcessRiskGridView.Rows.Count - 1
cmd_listview = New MySqlCommand(sQuery, conn)
cmd_listview.Parameters.AddWithValue("dat", DateTimePicker1.Value)
cmd_listview.Parameters.AddWithValue("process", ProcessRiskGridView.Rows(i).Cells(0).Value)
cmd_listview.Parameters.AddWithValue("avgrisk", ProcessRiskGridView.Rows(i).Cells(1).Value)
cmd_listview.Parameters.AddWithValue("riskafterimp", ProcessRiskGridView.Rows(i).Cells(2).Value)
cmd_listview.ExecuteNonQuery()
Next
End Using
conn.Close()
I tried for some mysql command but it didnt work.
You don't need to Select * to find out if a record exists. Just get the count. Don't retrieve data you don't need. You certainly don't need a reader.
Keep your database objects local so you can be sure they are closed and disposed. `Using...End Using blocks will handle this for you even if there is an error.
Don't use .AddWithValue See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
You keep adding parameters to the collection over and over on each iteration. They only need to be added once. The value of #dat remains the same for all iterations. Only the values of the last 3 parameters change. You seem to be mixing up column names and parameter names. We are dealing with parameter names.
I have guessed at datatypes. Check your database for the actual datatypes and be sure to convert the values from the grid cells to the proper type if necessary. I don't know what kind of grid you are using and if it returns proper datatypes for .Value.
Example:
cmd.Parameters("#avgrisk") = CDbl(ProcessRiskGridView.Rows(i).Cells(1).Value)
Private Sub MySql()
Dim retVal As Integer
Dim selectedDate = DateTimePicker1.Value
Dim startDate = New Date(selectedDate.Year, selectedDate.Month, 1)
Dim sQuery = "SELECT Count(*) FROM riskanalysis WHERE DateTimeColumnName >= #StartDate; "
Using conn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand(sQuery, conn)
cmd.Parameters.Add("#StartDate", MySqlDbType.DateTime).Value = startDate
conn.Open()
retVal = CInt(cmd.ExecuteScalar)
End Using
End Using
If retVal <> 0 Then
MessageBox.Show("Record Already Exist for this Month!")
Return
End If
sQuery = "INSERT INTO riskanalysis (reportdate, process, avgrisk, avgriskafterImp) VALUES (#dat, #process, #avgrisk, #riskafterimp);"
Using cn As New MySqlConnection("Your connection string")
Using cmd As New MySqlCommand(sQuery, cn)
With cmd.Parameters
.Add("#dat", MySqlDbType.DateTime).Value = selectedDate
.Add("#process", MySqlDbType.VarChar)
.Add("#avgrisk", MySqlDbType.Double)
.Add("#riskafterimp", MySqlDbType.Double)
End With
cn.Open()
For i As Integer = 0 To ProcessRiskGridView.Rows.Count - 1
cmd.Parameters("#process").Value = ProcessRiskGridView.Rows(i).Cells(0).Value
cmd.Parameters("#avgrisk") = ProcessRiskGridView.Rows(i).Cells(1).Value
cmd.Parameters("#riskafterimp") = ProcessRiskGridView.Rows(i).Cells(2).Value
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub

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...

Regarding to last_insert_id not working please help me

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

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