String Literal Escaping and Database - sql

I have been reading up on escaping strings to avoid SQL Injection. I do understand that parameterized queries are the safest way to avoid Injection.
But i do have a question regarding Escaping as means of complimenting Parameterized queries.
Suppose the input field "Name" had the value O'Brian and was escaped using the below routine:
sSanitizedInput = "'" & Replace(sInput, "'", "''") & "'"
So the value now looks like O''Brian. If this were to be inserted in the database using the Insert query, will the inserted value be actually O''BRIAN?
If that is the case, then in order to search the name column for the inserted value O''Brian, will i have to escape it to O''Brian before executing the Select query to match it with the value inserted in the DB?

Related

Regular Expression in SQL statement

I'm new in regular expression, and would like to ask help with the problem I have. I had a form, and it has drop down field where user can select one or more values, so the value for that drop down can be Faculty of Arts (if user chose one option) or Faculty of Arts, Faculty of Medicine (if user chose these two from the drop down).
Now, I want to convert this value, so that I can use it to filter my query. I will use this / these value(s) in WHERE clause. In this case, I have to reformat this value to "Faculty of Arts", "Faculty of Medicine", so it will fit in this statement:
SELECT * FROM myTable WHERE t_faculty IN ("Faculty of Arts", "Faculty of Medicine")
A friend of mine suggested me to try regular expression embedded in this SQL statement (I'm using SQL Server for the database). Do you have any idea on how to parse, and embed it in the SQL statement? Basically I need to add " characters in the beginning and end of the string, and replace the ,[space] with ",[space]" to get the wanted result.
Thank you!
Agus
You can split a comma-delimited string within SQL using STRING_SPLIT.
select * from myTable
where t_faculty in (
select value from string_split('Faculty of Arts, Faculty of Medicine', ',')
)
STRING_SPLIT returns a table of string values that are separated by the delimiter in the input string.
Otherwise you can use several pattern matching functions:
LIKE
PATINDEX
An SQL CLR (e.g.: C#) function that does expression matching. See SQL Server Regex.
You may also choose to simply split the string in your app. Then build the appropriate SQL command (or use something like Contains in linq).
You are not clear how you are passing those strings to SQL Server.
And SQL Server delimits strings with single quotes, i.e apostrophes not double quotes.
In whatever client-side code you have access to, simply concatenate the selected strings with apostrophes.
So if a user picks Faculty of Arts and Faculty of Medicine then you can join it all into one long string like
"'" & <selected option> & "'" & ",'" & <selected option> & "'"
You don't use regular expressions here to change the highlighted part of your SQL code :
SELECT FROM myTable WHERE t_faculty IN **("Faculty of Arts", "Faculty of Medicine")
I think your understanding about the way we use Regular Expressions could be wrong. You generally use regular expressions when you are trying to match with strings in your database which share some common properties. For instance if you have two rows with the fields "Faculty of Arts 1" and "Faculty of Arts 2". And you are trying to look up all the rows which have "Faculty of Arts" in general, then you could write it as SELECT * FROM myTABLE WHERE t_faculty LIKE 'Faculty of Arts*' where * would match anything after the text.
Instead of t_faculty IN (value1,value2), you will write something like t_faculty LIKE 'your regular_expression here'.

how to insert multiple row in single query in PostgreSQL

I have a variable that holds multiple data, and I want to insert this multiple data into PostgreSQL database using a single query.
the field on my table is this: stud_tbl(id,fname,lname)
and this is the variable that holds multiple data;
variable = (123,ron,lum),(234,nald,bay),(345,rol,lumz)
my query:
str = "insert into stud_tbl values ('" & variable & "')"
when I execute my query their was an error and I can't identify the error.
To expand on #Patrick's comment:
variable = "(123,'ron','lum'),(234,'nald','bay'),(345,'rol','lumz')"
the query:
str = "insert into stud_tbl values " & variable
Though the usual warnings (How can I prevent SQL injection in PHP?) about this not being best practice apply.
Value of your variable should be enclosed with quotation marks
variable = "(123,ron,lum),(234,nald,bay),(345,rol,lumz)"

How to delete contents of mulitple tables in Microsoft Access?

I need to clear the contents of multiple tables in an Access db using VBA.
Below is the code I am attempting to use, but it throws a "Syntax error in FROM clause." The SQL syntax (DELETE * FROM [table name];) works in a query.
Dim tbl As TableDef
Dim sqlstr As String
DoCmd.SetWarnings False
For Each tbl In CurrentDb.TableDefs
If tbl.Name Like "*_drop" Then
sqlstr = "DELETE * FROM " & tbl.Name
DoCmd.RunSQL sqlstr
End If
Next tbl
I found a similar problem and answer here, but it did not solve my problem.
I have also tried it without the sqlstr and received the same error.
For Each tbl In CurrentDb.TableDefs
If tbl.Name Like "*_drop" Then
DoCmd.RunSQL "DELETE * FROM " & tbl.Name
End If
Next tbl
You confirmed a query like this works without error.
DELETE * FROM [table name];
However the query your code builds does not bracket table name. Therefore, any table name which includes a space or contains nearly any character other than letters, digits, and underscore will result in a DELETE statement which triggers that error. If the table name matches a reserved word, that could also trigger the error. (Unfortunately it's difficult to predict exactly when reserved words will cause trouble.) It's safer to bracket all troublesome words in queries when they are used as field or table names. And for those which are troublesome because they are reserved words, you can alias them instead of bracketing.
But wherever practical, the safest practice is to rename all such objects: avoid reserved words; and use only letters, digits, and underscore.
Meanwhile, code defensively to cope with problem names. Revise the code to always bracket the table name.
sqlstr = "DELETE FROM [" & tbl.Name & "]"
I think you just need DELETE FROM without the *

Unable to select values when using a parameter for the column name

Try
Using connection As New SqlConnection(ConnectionString)
connection.Open()
SQL = "SELECT #PARAM FROM SystemOps"
sqlCmd = New SqlClient.SqlCommand(SQL, connection)
sqlCmd.Parameters.Add(New SqlClient.SqlParameter("#PARAM", SqlDbType.VarChar)).Value = "SystemNavn"
' .. and so on...
When I run the code, it returns with a result of "SystemNavn" (which is the name of the column in the table), instead of the value of that column in the current row. What am I doing wrong?
You cannot use parameter names for column names, or any other SQL syntax. You can only use parameters as placeholders for literal values. Parameters always get replaced with the literal form for the value, so in your example, the command which is being run, essentially, gets evaluated as:
SELECT 'SystemNavn` FROM SystemOps
In order to have a variable column name, like that, I would recommend dynamically building the SQL string, like this:
Dim columnName As String = "SystemNavn"
SQL = "SELECT [" & columnName & "] FROM SystemOps"
However, by doing so, you are opening yourself up to potential SQL-injection attacks, so you need to be careful. The safest way, that I'm aware of, to avoid an attack in a situation like this is to get the list of column names from the database and compare the columnName variable against that list to ensure that it is actually a valid column name.
Of course, if the column name never changes, then there's no reason to make it a variable at all. In that case, just hard-code it directly into the SQL command, thereby avoiding the necessity for parameters or variables at all:
SQL = "SELECT SystemNavn FROM SystemOps"
Your query doesn't need any parameters in this case. just do
SQL = "SELECT SystemNavn FROM SystemOps"
This is secure. If later you need to filter this, you can do something like:
SQL = "SELECT SystemNavn FROM SystemOps WHERE COL_A = #ColA"
FYI, for your code above, since it is a VARCHAR type, it is being executed like so:
SELECT 'SystemNavn' FROM SystemOps
That is why you're getting 'SystemNavn' back.
You cannot use a parameter to specify the name of a column or a table.
The parameters collection are used to specify the values to search for, to insert, to update or delete.
Your code should be changed to something like this
Using connection As New SqlConnection(ConnectionString)
connection.Open()
SQL = "SELECT SystemNavn, <other fiels if needed> " & _
"FROM SystemOps WHERE <keyfield_name> = #PARAM"
sqlCmd = New SqlClient.SqlCommand(SQL, connection)
sqlCmd.Parameters.AddWithValue("#PARAM", paramValue)
......
End Using
Of course the example above assumes that you have a WHERE clause, if you want to retrieve every value of the column SystemNavn without condition, then you don't need a parametrized query because every part of your sql command is provided by you and there is no worry for sql injection.

getting error on while inserting a single quotation values

Table1
EmpName1
Raja
Rav'i
Ramu'i
Rajes'ih
Table2
EmpName2
....
When I inserting table2.empname2 from table1.empname1, It inserted only the raja, remaining rows were not inserted it showing error in '(single quotation)
"Showing error as incorrect syntax near rav"
vb6 code.
INSERT INTO table2 (EmpName) VALUES('" & EmpName & "')
How can I insert a name with a single quotation also?
You can either escape your single quotation with something like
empName = replace(empName, "'", "''")
or paramertize your query...
It is highly recommended to use a parametrized query (see e.g. this article), instead of building your SQL query as a string. This protects you from many forms of SQL injection, and is also often faster.
Or directly use some kind of persistence framework, if you have a lot of DB interaction.
Your query will not work because in string SQL queries, the ' must be escaped (as ''). And BTW, if you want to insert values from one table into another, it is usually not a good idea to do a SELECT, then an INSERT in a loop, like you do. Just do a
INSERT INTO table2 SELECT ... FROM table1