简体   繁体   中英

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)
        conn.Open()
        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)
        cmd.ExecuteNonQuery()
    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!

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 .

Do not specify column names in apostrophies

Instead of

Dim cmdText = "INSERT INTO complete_log ('cust_id', 'business', 'note', 'date_stamp') values (@cid,@bus,@notey,@datey)"

Do

Dim cmdText = "INSERT INTO complete_log (cust_id, business, note, date_stamp) values (@cid,@bus,@notey,@datey)"

Change

INSERT INTO complete_log ('cust_id', 'business', 'note', 'date_stamp')

to

INSERT INTO complete_log (cust_id, business, note, date_stamp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM