Using variables in SQL queries in asp.net (C#) - c#

I have an SQL query of this form
string cmdText = "Select * from " + searchTable
+ "WHERE " + searchTable
+ "Name =' " + searchValue + "'";
Basically what I am trying to do is get a particular actor's info from the database's Actors table. The variable searchTable has the value 'Actor' which is the table name and searchValue has the actor's name (which is represented by the ActorName attribute in the Actor's table, here I am trying to form the name of the attribute by concatenating the words 'Actor' and 'Name' )
So, well, all this concatenation results in (or at least should result in) a query of the form:
Select * from Actor where ActorName ='some actor';
But when I try to run this it gives me the error "Incorrect syntax near '=' " in the browser. Could anyone please help?

You can put (and should!) parameters into your SQL queries for the values in e.g. your WHERE clause - but you cannot parametrize stuff like your table name.
So I'd rewrite that query to be:
SELECT (list of columns)
FROM dbo.Actor
WHERE ActorName = #ActorName
and then pass in just the value for #ActorName.
If you need to do the same thing for directors, you'd have to have a second query
SELECT (list of columns)
FROM dbo.Directors
WHERE DirectorName = #DirectorName
Using parameters like this
enhances security (prohibits SQL injection attacks!)
enhances performance: the query plan for that query can be cached and reused for second, third runs
PS: the original problem in your setup is this: you don't have any space between the first occurence of your table name and the WHERE clause - thus you would get:
SELECT * FROM ActorWHERE ActorName ='.....'
If you really insist on concatenating together your SQL statement (I would NOT recommend it!), then you need to put a space between your table name and your WHERE !
Update: some resources for learning about parametrized queries in ADO.NET:
The C# Station ADO.NET Tutorial / Lesson 06: Adding Parameters to Commands
Using Parameterized Queries with the SqlDataSource

You shouldn't concatenate string to SQL, as this will open you up to SQL Injection attacks.
This is a rather long read about dynamic SQL, but worth reading to understand the risks and options.
You should be using parameterized queries instead, though the only way to use a table name as a parameter is to use dynamic SQL.
I urge you to change your approach regarding table names - this will lead to problems in the future - it is not maintainable and as I mentioned above, could open you to SQL Injection.
The error you are seeing is a result of the concatenation you are doing with the "Where " clause - you are missing a space before it. You are also adding a space after the ' in the parameter ending with "Name".
Your resulting string, using your example would be:
Select * from ActorWHERE ActorName =' some actor';

There is a blank missing and one too much:
searchTable + "Name =' "
should read
searchTable + " Name ='"
Beside that, use SQL parameters to prevent SQL injection.

string cmdText = "Select * from " + searchTable + " WHERE Name = '" + searchValue + "'";

Related

ORA-01036 - illegal variable name/number

I have a dynamic SQL for searching records in Oracle, and VS2017 code analysis reports warning about using parameterized SQL query for this line (1st line, this code works):
string SQL = "SELECT " + string.Join(",", my_columns.ToArray()) + " FROM MyTable ";
string where_condition = " WHERE ";
//the rest of code follows as this...
if (!string.IsNullOrEmpty(textbox1.Text))
{
SQL = string.Concat(SQL, where_condition, " Name like :name");
cmd.Parameters.Add(new OracleParameter("name", string.Concat("%", textbox1.Text, "%")));
where_condition = " AND ";
} //...
So, I tried to put column names as parameters because of warning, but then I get ORA-01036- illegal variable name/number error:
string SQL = "SELECT :columns FROM MyTable ";
cmd.Parameters.Add(new OracleParameter("columns", string.Join(",",
my_columns.ToArray())));
string where_condition = " WHERE ";
What is wrong, maybe column names cannot be passed as parameters ? Or is there any other way to avoid warning in VS code analysis ?
You're right - column names can't be passed as parameters. That part has to be done dynamically, unless you want to change your database structure very significantly. (You could have one column with a value which is the logical column name, and one column for the value. I'm not recommending this - it's very much not how databases are intended to be used.)
The warning you're getting is there to avoid SQL injection attacks. When building the query dynamically, you have to do that differently. You basically need to make sure you have a whitelist of column names, and only build up SQL including those names.
You may well still get a code analysis warning at that point, but you should disable that just for this piece of code, with a comment explaining that you understand the warning, and what you've done to remove the risk of SQL injection attacks.

update stock quantity keeping along the previous quantity

I am having problem updating my database with stock. I want to add stock to the previous stock that is available in the inventory but error say that check your mysql Syntax before WHERE. and this is my query.
"UPDATE tblproducts SET Quantity=Quantity+'"+txtAddQty.Text+"' WHERE ProductId='"+txtProductId.Text+"' "
Where am i wrong. Help
You are concatenating Quantity and String (txtAddQty.Text)
"UPDATE tblproducts SET Quantity = Quantity + " + Convert.ToInt32(txtAddQty.Text) +
" WHERE ProductId='" + txtProductId.Text + "'"
Caution
Above SQL Statement fails if txtAddQty.Text gives alphabets instead of numeric value.
Also will fail if txtProductId.Text gives unexpected value
Not recommended way of doing things with database from application.
Instead of making sql statement by string concatenation you should use parametrized sql query. Doing so will prevent some of the sql injection problem.
imho, Quantity=Quantity+'"+txtAddQty.Text+"' will not work.
you need to remove those ' since you would add a varchar to an int
edit: You also could use a debugger to check the output of your string.
I guess Quantity is numeric, so you should remove the apostrophes ' in your string.
And please do not generate SQL-queries with string concatenation.Use parameterized queries: How do I create a parameterized SQL query? Why Should I?
Try removing the single quotes as you are trying to add it as a number. Only use quotes for strings.
Example:
UPDATE tblproducts SET Quantity=Quantity+"+txtAddQty.Text+" WHERE ProductId='"+txtProductId.Text+"' "

c sharp mysql underscore, space table name error

I'm trying to do a simple SELECT statement from a MySQL Database.
My table names contains underscores (_) and they could contain spaces ( ) as well. I put the table name in backticks but I get SQL Syntax error.
Example of one of my query:
"SELECT * From '" + ID + "_" + objectName + "' ORDER BY date DESC LIMIT 1"
If I do not use the backticks and the object name does not have any space in it, the query works.
Any idea what could be the problem?
You have not "put the table name in backticks", but rather in single quotes. Use instead:
"SELECT * From `" + ID + "_" + objectName + "` ORDER BY date DESC LIMIT 1"
Beware: having variable table names of this sort generally indicates that one's schema violates the Principle of Orthogonal Design, which can lead to a whole world of pain. You may wish to consider combining all such records into a single table, with a column whose value indicates whatever differentiation exists between the existing tables.

How to protect against SQL Injection with OdbcCommand when the query is not parameterized?

I am writing a generic sqldump utility that takes a DSN and a table name and dumps the contents to a file. It's an internal app so SQL Injection is not a serious threat, but I don't want to have to worry about it. The thing is, the variable part of the query is actually the tablename, so the query is going to look like:
select * from [tablename];
...which I don't imagine will work well with the OdbcCommand's parameterized query support. I am also trying to support all types of DSN's as generically as I can, regardless of the driver on the other side of the DSN.
Is there some universal way to sanitize my tablename input to protect against all SQL Injection using the OdbcCommand object?
I'd check the user input against the list of tables you know are there, using code roughly like what's posted here to retrieve the table list (code from the link included for posterity):
class Program
{
static void Main(string[] args)
{
string connectionString = GetConnectionString();
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Connect to the database then retrieve the schema information.
connection.Open();
DataTable table = connection.GetSchema("Tables");
// Display the contents of the table.
DisplayData(table);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
That said, I agree with #KeithS above. This is probably a Bad Idea.
The only special character in a [] quoted identifier for SQL Server is ], and it can be escaped by passing ]]. So for that, "select * from [" + tableName.Replace("]", "]]") + "];" should be safe. Other systems, however, may use other escape mechanisms, so this is not a full solution if you want to connect to a different type of database.
Alternatively, consider each character, and see if it is a valid character for table names you wish to support. If you say table names only contain letters, digits, and/or whitespace, then SQL injection is not possible, because you'll never be able to unquote the [quoted table name].
You could first query the information_schema to find out if the table exists:
select *
from information_schema.tables
where table_schema = #your_database_name and table_name = #table_name
This query can be parameterized and is NOT prone to SQL injections.
Following that, you can issue your select * from #table_name query.
If the table name is enclosed in [ ] then just do not allow table names to contain "]". ] could be used by malicious people to terminated the sql command and to introduce dangerous code.
If you are constructing the sql like this
string sql = "SELECT * FROM [" + tablename + "]";
and the tablename is defined like this
string tablename = "tablename]; DELETE FROM [tablename";
The resulting sql becomes
SELECT * FROM [tablename]; DELETE FROM [tablename];
However, this is only possible if the table name contains a ].
Note:
If you are replacing string values like this, then replacing a single quote by two single quotes makes it safe too.
string sql = "SELECT * FROM tbl WHERE Name = '" + input.Replace("'","''") + "'";

Dynamically taking a table name in aspx form using sql server

I'm trying to dynamically accept a table name depending on the conditions satisfied, also the column name is selected dynamically, and so is the comparison value, but I'm getting an error while running it. I'm writing this code in C# and my backend is SQL server 2005. Please help me.
Here is the code:
if( table=="studenttab")
table = "personal_detail";
thisconnection1.Open();
string p = field[0].ToString().ToLower();
string q = code[0].ToString();
SqlCommand thiscommand3 = thisconnection1.CreateCommand();
thiscommand3.CommandText = " Select * from '" + table + "' where '" + p + "' = '" + q + "' ";
// here it gives error "Incorrect syntax near 'personal_detail'." Dont understand!
SqlDataReader thisreader3 = thiscommand3.ExecuteReader();
To answer your specific question, I would guess the error is due to the fact that you are surrounding your table name and column names with single quotes. your object names should not be surrounded with quotes of any kind.
As a side note, please look into the problems associated with SQL injection attacks. The kind of SQL concatenation you are doing here is widely considered a huge security risk.
Your code is missing several closing braces, a closing quote, and it seems to have misleading indentation.

Categories

Resources