0

I would like to insert a row with SQL (in Visual Basic) and receive something like: "Error: You have an errin in your SQL syntax near IF NOT EXISTS ... at line 1"

Code looks like:

...
Try

    query = "IF NOT EXISTS (Select Movie_Name from MovieDB where Movie_Name=" & placeholder & ") INSERT INTO MovieDB (Movie_Name) VALUES ('" & placeholder & "')"

    'PREPARE CONNECTION
    MySQLCmd = New MySqlCommand(query, dbConnection)

    'OPEN DB 
    dbConnection.Open()

    'EXECUTE QUERY
    MySQLCmd.ExecuteNonQuery()

    'CLOSE DB
    dbConnection.Close()

Catch ex As Exception
    ...

I really dont get it anymore. Some ideas?

4
  • Where are you getting placeholder from, and what does it contain? Commented Oct 23, 2014 at 19:39
  • Is this Visual Basic.NET or VBA? Commented Oct 23, 2014 at 19:47
  • @DStanley vba doesn't have Catch, so this is VB.Net Commented Oct 23, 2014 at 19:53
  • placeholder is a value from checkbox. When I check from a checkbox-list some movies, in placeholder will be the name of the checkbox (moviename) like "ABC.mkv". Commented Oct 23, 2014 at 20:17

2 Answers 2

1

At a minimum you need single quotes around the first string as well:

                                                                      --V                 --V
query = "IF NOT EXISTS (Select Movie_Name from MovieDB where Movie_Name='" & placeholder & "'); INSERT INTO MovieDB (Movie_Name) VALUES ('" & placeholder & "')"

As @Cameron astutely noticed, you also need a semicolon between the EXISTS function and the INSERT command

But you should look into using parameters instead of concatenating SQL - not only does it remove the need to delimit strings, but it prevents SQL injection and avoids syntax error if the string contains an apostrophe.

Sign up to request clarification or add additional context in comments.

1 Comment

with the code above i receive this: Error: writeToDB 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 'IF NOT EXISTS (Select Movie_Name from MovieDB where Movie_Name='Enemy 2.mkv'' at line 1. I think there is now a ' to much...?
0

As far as I know "IF NOT EXISTS INSERT" is no valid MySQL syntax. This should work:

query = "INSERT INTO MovieDB (Movie_Name) VALUES ('" & placeholder & "') ON DUPLICATE KEY UPDATE Movie_Name = Movie_Name";

This tries to insert the new movie name and if this fails it does virtually nothing. (For this to work there must be a unique index on Movie_Name.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.