Friday, March 9, 2012

how can I insert a semicolon as user data?

I'm working with an existing program that crafts an insert statementfrom user input. The data is machine generated, though, and someof it has semicolons. How can I "escape" those semicolons so thatI can insert them into the database? Does the ESCAPE key workwith the insert statement, too? Can I just replace the ";" withsome other character(s) to escape it? I'm not finding much in theonline help. Thanks!
If by "craft" you mean concatenating strings to create a SQL statement...you should not do that.
If you build a parameterized sql statement, then the semi-colons would not be an issue.|||ie, you mean use a stored procedure, right? yes, they're usingjust a "crafted sql statement right now - "insert into blah blah blah"and then filling in the parameters. its a console app inc#. I was going to try and just do a replace on the insertstatement, but now i think i might just go and redo the whole thing asa stored procedure. but if I were going to replace the ";" withinan insert statement, how would that work, or can't it be done?
|||Can you post how your INSERT statement looks like. This will give a better idea what you are planning to do!
|||If the semi-colon is properly quoted, it should be ok. It's usually the quotes that get you when you concatenate.
As far as creating a stored-proc goes, you can execute parameterized sql statements without taking it all the way to a stored-proc.
for example:
"UPDATE someTable SET someField=@.p1"
Then when you create the command object, you simple need to add a parameter named @.p1 and give it a value.
Since @.p1 is a parameter, even if its string data, it does not need to be quoted.
With parameterized sql, you get the benefit of ad-hoc queries with the safety (from sql injection) of a stored proc.
Also, when parameterized sql statements are sent to sql server, the execution plan can be cached improving performance.
For example: "SELECT someFields FROM someTable WHERE someId=@.p1"
In the previous statement, the same execution plan would be reused if you needed to issue that query multiple times for multiple values of someId.
This - on the other hand: "SELECT someFields FROM someTable WHERE someId=5"
would only get reused if you keep querying for someId=5

Note: The Microsoft DAAB (Data Access Application Block) can be especially usefull for issuing queries.
|||Actually, a parameterized statement was what was being done originally,so I'm not sure now. I changed things to an actual storedprocedure, but the original problem is still occurring, so maybe itsnot the semicolon after all. The error I'm getting is
"System.IndexOutOfRangeException: Index was outside the bounds of the array.
at SmatFileReader.SmatReader.Main(String[] args)"
I'm not fully sure what that means. I'm trying to debug it now...any ideas?

No comments:

Post a Comment