SQL Insert Command - Field with Punctuation

  • Thread starter Thread starter B-Dog
  • Start date Start date
B

B-Dog

I have a vb form that I'm using to insert some data off the fields in the
sql server but if any of the field have punctuation like comma, dash,
apostrophe's it throws an error on insert. Any ideas, why? All the fields
in the database and dataset except for ID and Date are strings. Here is my
insert command. Thanks

Dim sqlInsert As String = "INSERT INTO Files ( FileName, Link, Description,
WO, sTo, WONumber, " _
& "Client, FileTo, FileFrom) SELECT '" & filename & "', '" & link & "', '" &
fDescription.Text & "', '" & wo & "', '" _
& fDistribution.Text & "', '" & woNumber & "', '" & client & "', '" &
fTo.Text & "', '" & fFrom.Text & "'"
 
Don't use string concatenation from queryes, it's a bad pratice.

Use somewath like this:

Dim sqlInsert As String = "INSERT INTO Files ( FileName, Link, Description,
WO, sTo, WONumber, Client, FileTo, FileFrom) VALUES( @FileName, @Link,
@Description,
@WO, @sTo, @WONumber, @Client, @FileTo, @FileFrom)

Dim cmd as SqlCommand=new SqlCommand(sqlInsert ,connection)

cmd.Parameters.Add("@FileName",filename)
cmd.Parameters.Add("@Link",link)
.....
cmd.ExecuteNonQuery()

It should work.
I suggest you to use always parameters instead of string concatenation.

Excuse me for my bad english.
 
Add a Semicolon at the end of each line and just change the declaration ie
SqlCommand cmd = new SqlCommand(sqlInsert, connection);

Definitely want to avoid the dynamic sql - nothing but drama if you're not
using parameters.
 
Thanks, I'll give it a try.


Cirrosi said:
Don't use string concatenation from queryes, it's a bad pratice.

Use somewath like this:

Dim sqlInsert As String = "INSERT INTO Files ( FileName, Link, Description,
WO, sTo, WONumber, Client, FileTo, FileFrom) VALUES( @FileName, @Link,
@Description,
@WO, @sTo, @WONumber, @Client, @FileTo, @FileFrom)

Dim cmd as SqlCommand=new SqlCommand(sqlInsert ,connection)

cmd.Parameters.Add("@FileName",filename)
cmd.Parameters.Add("@Link",link)
....
cmd.ExecuteNonQuery()

It should work.
I suggest you to use always parameters instead of string concatenation.

Excuse me for my bad english.
 
Back
Top