error in mysql syntax in vb.net - mysql

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)

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

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

Having problems crafting SQL statements to get tables and values in JSP

conn = DriverManager.getConnection(connURL);
String sqlStr = "Select * from inventory where functions" + "like ? order by brand, model";
PreparedStatement pstmt = conn.prepareStatement(sqlStr);
pstmt.setString(1, "%" + search + "%");
ResultSet rs = pstmt.executeQuery();
Hi guys, i am having error with this code at line 2 and line 4. I believe that my coding contains errors.
I have a doubt that my SQL query is not correctly formatted. The pstmt.setString will set the search value to the ? in the SQL query.
The error:
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 ''%null%' order by brand, model' at line 1
The syntax of your sql query declaration is wrong. That is why you're getting that error. Why are you including + in between ?
Try
conn = DriverManager.getConnection(connURL);//this is bad use a connection pool
StringBuilder sb = new StringBuilder().append("Select * from inventory where functions");
sb.append(" like ? order by brand, model");
String sqlStr = sb.toString().intern();//use intern if this function is used many times

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

I need the metadata from a mysql resultset, is this possible?

I'd like to obtain the metadata from the results of a mysql query so I can put it into a datatable in c#. I primarily need the column name and the data type. Here's a simple example.
show columns from (
select sum(subtotal) as subtotal
, sum(tax1+tax2+tax3+tax4) as tax
, sum(subtotal)+sum(tax1+tax2+tax3+tax4) as total
from tbltransmaster
where batchnum in (
SELECT BatchNum
FROM tblshiftmaster
WHERE ClosingTS <> -1
ORDER BY OpeningTS ASC
)
) as x
It generates this error though
Error Code : 1064 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 '(
select sum(subtotal) as subtotal
, sum(tax1+tax2+tax3+tax4) as tax
, sum' at line 1
Could someone provide me with some advice, or perhaps a link to assist with this?
show columns only works for actual tables and views, not for queries.
Since you mention C#, you're probably using ADO.NET ? You can directly fill a DataTable which figure out the data types and column names.
DbConnection conn = null;
DbConnection conn = null;
DbCommand cmd = null;
DbDataAdapter da = null;
DataTable tbl = new DataTable();
conn = new MySqlConnection(connectionString);
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = query;
da = new MySqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(tbl);
If you want to get the colum names only, you could fetch the result using a DataReader instead:
DbDataReader dbReader = cmd.ExecuteReader();
for (int i = 0; i < dbReader.FieldCount; i++) {
Type colType = dbReader.GetFieldType(i);
String colName = dbReader.GetName(i);
}
DbDataReader also have the .GetSchemaTable() which returns a DataTable describing the metadata of the result.