Feign Feign - 1 year ago 57
MySQL Question

How to insert to mysql from asp.net using vb?

I am trying to insert into a mysql table. Here is my code...

Dim cmdText = "INSERT INTO complete_log ('cust_id', 'business', 'note', 'date_stamp') values (@cid,@bus,@notey,@datey)"
Dim conn As New MySqlConnection("server=theipofserver;user id=id;password=mypass;database=thedatabase")
Using cmd = New MySqlCommand(cmdText, conn)
Dim testy As String
testy = TextBox1.Text
Dim dater = Date.Today + TimeOfDay
cmd.Parameters.AddWithValue("@cid", c_id)
cmd.Parameters.AddWithValue("@bus", c_business)
cmd.Parameters.AddWithValue("@notey", testy)
cmd.Parameters.AddWithValue("@datey", dater)
End Using

But, I get the following error:

MySql.Data.MySqlClient.MySqlException: 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 ''cust_id', 'business', 'note', 'date_stamp') values ('ID','null','first one'' at line 1

the table I am trying to insert into has 4 columns that are all varchars with plenty of space (varchar(100))

Here are more details on the error... error occurs on line 31...

Line 29: cmd.Parameters.AddWithValue("@notey", testy)
Line 30: cmd.Parameters.AddWithValue("@datey", dater)
Line 31: cmd.ExecuteNonQuery()
Line 32: End Using
Line 33: TextBox1.Font.Bold = True

So, what am I doing wrong here? Any tips on better ways to insert into mysql tables would be greatly appreciated!

Answer Source

Don't use quotes around table or column names.

INSERT INTO complete_log (`cust_id`, `business`, `note`, `date_stamp`)
values (@cid,@bus,@notey,@datey)

If you want to escape table and column names then use backticks. But you only need to escape reserved words in MySQL.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download