0

I need to insert new record into a SQL Server database, but get

Incorrect syntax error

The strange thing is when I try to query the same statement in SQL Server itself, it works properly.

The code in vb.net is as follows:

insertSql = "INSERT INTO Seg_LINE VALUES (" & OBJECTID & ", 'test" + "', '" + "test" + "','" + DrainName + "'," & UID & ")"
logger.Info("insert sql = " + insertSql)
Dim cmdInsert As New SqlClient.SqlCommand(insertSql, Sqlconnection) 
cmdInsert.ExecuteNonQuery()

The OBJECTID and UID are number parameters.

I cannot figure out what's wrong with my code, I am using vb.net(vs2102).

3
  • 1
    This code is vulnerable to sql injection attacks... it's practically begging to get hacked. Commented Oct 17, 2014 at 3:21
  • What is the SQL Statement output of the logger.Info? Commented Oct 17, 2014 at 3:32
  • Hi, the sql statement logged is : insert sql = INSERT INTO Seg_LINE VALUES (635,'test','test','Kallang',93571) Commented Oct 17, 2014 at 3:55

1 Answer 1

2

Most likely you have a DrainName value with a single quote in it. You're lucky the query is just failing, and not executing unwanted commands on your DB server. Don't use string concatenation like that to build queries! You need to use query parameters, like this:

insertSql = "INSERT INTO Seg_LINE VALUES (@ObjectID, 'test', 'test', @DrainName, @UID)"
logger.Info("insert sql = " + insertSql)
Dim cmdInsert As New SqlClient.SqlCommand(insertSql, Sqlconnection)
'I'm guessing at these parameter types. Use the actual db types of the columns
cmdInsert.Parameters.Add("@ObjectID", SqlDbType.Int).Value = OBJECTID
cmdInsert.Parameters.Add("@DrainName", SqlDbType.NChar, 50).Value = DrainName
cmdInsert.Parameters.Add("@UID", SqlDbType.Int).Value = UID
cmdInsert.ExecuteNonQuery()

Changing the code this way will also likely fix your syntax error.

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

3 Comments

Hi Joel, thanks a lot for the reply, but the result is the same. When I tried to create a new function and use the same code, it works properly.
Another thing to mention is although there has error, the data is store into the db table, but the program not proceed further.
Hi Joel, when I change ExecuteNonQuery to ExecuteScalar, it works properly, thanks for the attention.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.