Dynamically taking a table name in aspx form using sql server - c#

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.

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+"' "

Escape special characters in SQL INSERT INTO via C#

I have searched google and haven't found any solution for my issue yet. Basically I have a comments feed that is setup within an image gallery (similar to facebook or stackoverflow comments). Users can post comments and read comments posted by other users. This is working fine. However, if a user tries to post a comment with an apostrophe, I get a nice little web application error:
Incorrect syntax near 's'. Unclosed quotation mark after the character
string ')'.
The comment that I'm posting to SQL is 81's. I'm wanting a solution that will escape all special characters so that whatever the user types in, no matter what, doesn't error out.
Code Behind
Fetcher.postUserComments(connectionString, imagePath, comments.ToString(), userId);
Fetcher
sqlCom.CommandText = "INSERT INTO dbo.Table(userId, imagePath, userComments, dateCommented) VALUES ('" + userId + "', '" + imagePath + "', '" + comments + "', '" + theDate + "')";
The data type is string and I've also tried doing a .ToString() but no luck. Thanks in advance for any helpful input.
You should always use parameterized querys. They help you avoid situations like the one you are having, as well as SQL Injection attacks
sqlCom.CommandText = "INSERT INTO dbo.Table(userId, imagePath, userComments, dateCommented) VALUES (#userId, #imagePath, #userComments, #dateCommented)";
sqlCom.Parameters.AddWithValue("#userId", userId);
sqlCom.Parameters.AddWithValue("#imagePath", imagePath);
sqlCom.Parameters.AddWithValue("#userComments", comments);
sqlCom.Parameters.AddWithValue("#dateCommented", theDate);
You need to duplicate the ' character in comments
comments = comments.Replace("'", "''");
Alternatively, but more safety, is to use Sql parameter, example :
cmd.CommandText = "SELECT * FROM Client, Project WHERE Client.ClientName = #ClientName AND Project.ProjectName = #ProjectName";
cmd.Parameters.Add(new SqlParameter("#ClientName",client.SelectedValue));
cmd.Parameters.Add(new SqlParameter("#ProjectName",projnametxt.Text));
You should NEVER do this...because it allows for easy SQL injection. I could inject malicious sql queries through a comment, something like...
;drop database master;
use parameters instead to avoid sql injection
command.Parameters.Add(new SqlParameter("#Param", value));

Using variables in SQL queries in asp.net (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 + "'";

Updating Excel Cell with Non-Numeric Data in C#

I have a query that is
ExcelQuery = "Update [Sheet1$] "
+"set CITIZEN_ID = #" + value
+ " where CITIZEN_ID = " + value;
As you can see, I'm essentially just prepending a "#" to the CITIZEN_ID field. value is a int/numeric value. So if I had "256" in the CITIZEN_ID column it would be converted to "#256"
When I execute this I get an OleDbException Syntax error in date in query expression so I surrounded part of the query in single quotes like this,
ExcelQuery = "Update [Sheet1$] "
+"set CITIZEN_ID = '#" + value + "' "
+"where CITIZEN_ID = " + value;
With that I get yet another OleDbException this time with, Data type mismatch in criteria expression.
I'm guessing for some reason the CITIZEN_ID fields don't want to take anything besides a plain number. Is there any way I can remedy this to get that pound symbol in?
Thanks!
Can't you just change the number format so it shows a '#' before each number in the CITIZEN_ID field.
This doesn't solve your stated problem .. but it avoids it :-)
Update:
This StackOverflow Question ( excel-cell-formatting) talks about cell formatting using C#
It sounds like you are trying to use SQL to INSERT a text value into a column which the DBMS (the Access Database Engine) sees as DOUBLE FLOAT and hence getting a type mismatch error. You may be able to change registry values to convince the engine to consider the column to be text, see:
External Data - Mixed Data Types

Categories

Resources