not getting the insert data in mysql using visual basic - mysql

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

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

How to insert values from another table

I am inserting two values to a table, one from another table and the other from form control but I am getting an error.
sqlstr = "INSERT INTO partylinks ( accountid, partyid ) values(Select max(accountsinfo.accid) FROM accountsinfo,2 )"
cmd = New OleDb.OleDbCommand(sqlstr, con, tra)
cmd.ExecuteNonQuery()
You don't use the VALUES syntax if you are SELECTing
Try:
sqlstr = "INSERT INTO partylinks (accountid, partyid) Select max(accountsinfo.accid),2 AS partyid FROM accountsinfo"

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

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

error in mysql syntax in vb.net

I get this error, while I'm testing the code below:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[student](ID, LASTNAME, FIRSTNAME, SCHOOL) VALUES ('333', 'aaa', 'aaa', 'aaa')' at line 1
I just recycled the code that I used in manipulating ms sql database. So the syntax must be wrong. What might be the correct syntax for adding records into mysql database?
Here is my current code:
idnum = TextBox1.Text
lname = TextBox2.Text
fname = TextBox3.Text
skul = TextBox4.Text
Using sqlcon As New MySqlConnection("Server=localhost; Database=testing;Uid=root;Pwd=nitoryolai123$%^;")
sqlcon.Open()
Dim sqlcom As New MySqlCommand()
sqlcom.Connection = sqlcon
sqlcom.CommandText = "INSERT INTO [student](ID, LASTNAME, FIRSTNAME, SCHOOL) VALUES (#ParameterID, #ParameterLastName, #ParameterFirstName, #ParameterSchool)"
sqlcom.Parameters.AddWithValue("#ParameterID", TextBox1.Text)
sqlcom.Parameters.AddWithValue("#ParameterLastName", TextBox2.Text)
sqlcom.Parameters.AddWithValue("#ParameterFirstName", TextBox3.Text)
sqlcom.Parameters.AddWithValue("#ParameterSchool", TextBox4.Text)
sqlcom.ExecuteNonQuery()
End Using
Please help, thanks
Try removing the square brackets from the student table name, and adding a space between table name and column list: [student] (ID, ...
Without your table schema definition I can't be 100% sure, but ParameterID appears to be an int, but you are passing as a string (i.e. value is wrapped in single quotes). Try converting TextBox1.Text to an int first (using Try.Parse)