How do I parameterize a DB2 ODBC query using C#? - c#

I have a problem trying to parameterize some "dynamic" SQL build in an existing C# class used by an ASP app. The environment is:
Win Server 2008
.NET 3.0
C#
DB2 9.x ([IBM][CLI Driver][DB2])
The existing code just concatenates the SQL with the param strings in a long SQL string - which is of course at risk for SQL injection. As is my practice whenever I see this, I tend to change the code to use parameters. But with this code I am failing. I have tried "#" and I have tried "?" - the latter is what I understand to be necessary for ODBC.
Here is a simplified code snippet (forgive me if I don't format it right - this is my first question) that I have compiled and run:
private DataSet test(String schemaName )
{
String sortField = "TABLE_NAME.COLUMN_NAME";
String sortDirection = "ASC";
OdbcConnection conn = new OdbcConnection();
DataSet ds = new DataSet();
string connStr = ConfigurationManager.AppSettings[schemaName] + dbUser;
try
{
conn.ConnectionString = connStr;
OdbcCommand cmd = new OdbcCommand("SELECT * FROM TABLE_NAME ORDER BY ? ? ");
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(sortField);
cmd.Parameters.Add(sortDirection);
logger.log("cmd SQL = \t" + cmd.CommandText );
OdbcDataAdapter da = new OdbcDataAdapter(cmd);
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
ex.Data.Add("Location:", "test()");
ex.Data.Add("Connection", conn.ConnectionString);
logger.logException(ex);
throw ex;
}
finally
{
conn.Close();
}
}
Log printout:
cmd SQL = SELECT * FROM TABLE_NAME ORDER BY ? ?
Where TABLE_NAME is of course the table I am querying.
What I get in return is this (some proprietary info removed:
EXCEPTION occured at 4/26/2012 12:29:41 PM ERROR [42601] [IBM][CLI
Driver][DB2] SQL0104N An unexpected token "?" was found following "".
Expected tokens may include: "MICROSECONDS MICROSECOND SECONDS SECOND
MINUTES MINUTE HOURS". SQLSTATE=42601
at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)Connection Driver={IBM DB2 ODBC DRIVER};
.....
Changing this to a stored proc is not allowed.
Upgrading to a later version of .NET is not allowed.
Changing/upgrading the ODBC driver is not allowed.
What I am seeing indicates to me that the "?" parameter is not being replaced.
I have tried AddWithValue() and I have tried Add(OdbcType.VarChar).Value = sortField (or something to that effect).
I am kind of at my whit's end - all of the googling and searching here indicates to me that the code above should work, but so far I have not been able to get the parameters in the SQL substituted with the variables.
Thanks in advance.

The reason the ? is an unexpected token is because you are using it in the ORDER BY clause (which I don't think is allowed).
The reason to use parameters is to mitigate the risks of user input. When building your query, if the ORDER BY field and direction are not coming via user input, you are safe in building the query with concatenation.
Only use the ? in the WHERE clause:
OdbcCommand cmd = new OdbcCommand("SELECT * FROM TABLE_NAME WHERE ID = ? ORDER BY " + sortField + " " + sortDirection);

Related

SQL injection prevention with 'AS QUERY'

I have the following code which seems pretty standard on face value, however in query is another SQL statement hence why the 'AS QUERY' is at the end of the SQL string. I wanted to know if there was a sophisticated approach to parameterising the following SQL command instead of concatenating the entire query together.
The only solution I could think of would be to instead of having a query as a string, have it as an SQLCommand type object and initiate 2 commands. 1 to could and the other to display the preview of the data.
public static CommandStatus<int> GetQueryRecordCount(SqlConnection connection, String query)
{
String sql = "SELECT COUNT(1) FROM (" + query + ") AS QUERY";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = connection;
cmd.CommandTimeout = GetTimeout();
try
{
SqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();
String count = dataReader[0].ToString();
dataReader.Close();
return new CommandStatus<int>(Int32.Parse(count));
}
catch (Exception e)
{
return new CommandStatus<int>("Failed to GetQueryRecordCount[" + sql + "]:" + e.Message, e);
}
}
String SQL will end up being something like this
"SELECT COUNT(1) FROM (SELECT TOP 20 [RecordID],[Name],[SonsName],[DadsName],[MothersName],[DaughtersName] FROM [dbo].[sample] ) AS QUERY"
This function is literally SQL injection by design.
Whitelisting the SQL queries this function will accept is the only way to make it safe.
That is, the caller won't be able to inject any SQL query, they'll only be able to pick from a fixed list of pre-vetted queries. The list could even be defined as an array of static strings in the function you show.
But then they don't need to pass the whole query as a string, they only need to pass an ordinal integer to identify which query in the whitelist to run.

not able to load odbcdatareader to a datatable

I am using an Informix db, and I am trying to get data for a specific item and store it in a datatable.
I checked the following:
1) connection string looks good
2) the connection is able to open
3) I used the same connection string from the web.config on a dataset creating a table adapter and it is able to retrieve the record.
This is the code I am using:
var connectionstring = ConfigurationManager.ConnectionStrings["TestDataTable"].ConnectionString;
OdbcConnection con = new OdbcConnection(connectionstring);
//con.ConnectionString = connectionstring;
if (TxtItem.Text != hold_item)
{
con.Open();
OdbcCommand cmd = new OdbcCommand(#"Select t_item,t_idsc,t_upct,
t_item_upc,t_ctyp,t_citg,
t_best,t_disp,t_mold,t_csel
from informix.tsckcm907
where t_item = " + stitem, con);
OdbcDataReader myReader = cmd.ExecuteReader();
DataTable testdt = new DataTable();
testdt.Load(myReader);
foreach (DataRow row in testdt.Rows)
{
lbldesc.Text = row["t_idsc"].ToString();
Spanish_Item();
{
DropDownList2.SelectedIndex = 1;
object stlanguage = 1;
hold_language = Convert.ToString(stlanguage);
TxtBestBefore.Text = row["t_best"].ToString();
holdbest = Convert.ToInt16(TxtBestBefore.Text);
}
}
myReader.Close();
myReader.Dispose();
cmd.Dispose();
con.Close();
con.Dispose();
}
in debug mode my error occurs at the OdbcDataReader line:
error message:
An exception of type 'System.Data.Odbc.OdbcException'
occurred in System.Data.dll but was not handled in user code
Additional information: ERROR [42000] [Informix]
[Informix ODBC Driver][Informix]A syntax error has
occurred.
If your Informix ODBC driver says: "A syntax error has occurred" then you have to check your SQL statement:
"Select t_item,... from informix.tsckcm907 where t_item = " + stitem
I think that something is wrong with stitem. We don't know what type and value it is, but if its type is some kind of string or date then it may be in the wrong form. Easiest way is to extract full SQL statement (simply print it before execution) and use it with some database editor (for example db_access from Informix). Then make it work in SQL editor and transform stitem variable into acceptable form (add quotes, escape internal quotes, escape special characters etc.)
I also recommend use of PreparedStatement that separates your query from data. This way you do not need to worry about stitem form. No quotes, no escaping, just place holder in query string and value added separately.
I don't use C# but I see that C# can work with preapred statements with unnamed parameters:
cmd.CommandText = "SELECT ... FROM ... WHERE t_item = ?";
cmd.Parameters.Add("#t_item", ObdcType.VarChar, 200).Value = t_item;
or with named parameters:
cmd.CommandText = "SELECT ... FROM ... WHERE t_item = #t_item";
cmd.Parameters.Add("#t_item", ObdcType.VarChar, 200).Value = t_item;
I use unnamed parameters from ODBC so Informix driver can work with such parameters but you will have to check it yourself with C#.

C# SQL string formatting

I am new to .net/C#. Coming from PHP and some Java, I am finding the new languages interesting and challenging.
I have an issue with a sql string
string query = #"select * from Users where role='member' and
SUBSTRinG(lname, 1, 1) = '"+querystring + "' ORDER BY lname ASC";
Which to me, looks fine. however when run my solution and output the query as it is not working, I get this as my output:
select * from Users where role='member' and SUBSTRinG(lname, 1, 1)
= ' O ' ORDER BY lname ASC
This is output into my Firebug console (the page that uses this query is accessed via AJAX).
Is their a reason my 's are being turned into their code version, ie '&#39'
Thanks
In C# you should be using SqlCommand to excute the query, and to prevent sql injection using the parameter collection.
Your query seems fine - The issue might be the way you are running it or the parameters being supplied. Update your question with more details on what you are expecting vs what is happening, include any error messages generated.
Below is a general guideline of how to get data from a sql table to a c# Data Table object.
SqlConnection conn = new SqlConnection("YourConnectionString");
SqlCommand cmd = new SqlCommand(#"select * from Users where role='member' and
SUBSTRinG(lname, 1, 1) = #query ORDER BY lname ASC");
cmd.Parameters.AddWithValue("#query", querystring);
DataTable resultTable = new DataTable();
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(resultTable);
} finally {
if (conn.State != ConnectionState.Closed) conn.Close();
}
Console.WriteLine(String.Format("Matched {0} Rows.", resultTable.Rows.Count));
For SQL injection protection:
You can provide escape sequence for single quotes by replacing them with two single quotes '' so that it will be treated as a single quote inside SQL strings. Otherwise it is considered as a start or end of the string value in SQL.
Replacing single quotes using ' in .net is also preferred but its better going with two single quotes.

How can I get values from database

I tried to get values from access data base with two where clause. This is the error that I got!
"Syntax error (missing operator) in query expression 'unit1<=34 and unit2>=34 where"'.
and this is my code:
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\Work\\Office\\Electricity_Board_bill_calculator\\gk.accdb;");
con.Open();
OleDbCommand com5 = new OleDbCommand("select id from tblBillConfig where unit1<="
+ contot + " and unit2>=" + contot + " where group=3 ", con);
You have 'where' in 2 places of the SQL string. This is at least one reason for the error.
There are a couple of potential issues:
You can't have 2 where clauses. The second filter needs to be introduced with and`
Group is a reserved keyword, so and needs to be escaped. (This would be [group] in Sql Server. I'm not sure how to do this in MS Access)
You should also look at using parameters to bind variables. This addresses a bunch of issues, such as sql injection, and also improves performance as the parameterization may allow your RDBMS to cache the query plan.
So your query should look something like this:
var com5 = new OleDbCommand("select id from tblBillConfig " +
" where unit1<=? and unit2>= ? and [group]=3 ", con);
command.Parameters.Add("#p1", OleDbType.Integer).Value = 34;
command.Parameters.Add("#p2", OleDbType.Integer).Value = 34;

ExecuteScalar always returns 0

I'm not sure why this is happening. I've seen the same issue online with little help out there to correct it.
When i run my query inside Access i get different values ranging from 0 - 10 but for some reason, it won't return that same value inside my code.
static int OrdersPerHour(string User)
{
int? OrdersPerHour = 0;
OleDbConnection conn = new OleDbConnection(strAccessConn);
DateTime curTime = DateTime.Now;
try
{
string query = "SELECT COUNT(ControlNumber) FROM Log WHERE DateChanged > #" + curTime.AddHours(-1) + "# AND User = '" + User + "' AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered');";
OleDbCommand dbcommand = new OleDbCommand(query, conn);
dbcommand.Connection.Open();
dbcommand.CommandType = CommandType.Text;
dbcommand.CommandText = query;
OrdersPerHour = (int?)dbcommand.ExecuteScalar();
}
catch (OleDbException ex)
{
}
finally
{
conn.Close();
}
return OrdersPerHour.Value;
}
Do not use string concatenation and the Access syntax to build your sql commands.
Use a simple parameterized query like this
string query = "SELECT COUNT(ControlNumber) FROM Log " +
"WHERE DateChanged > ? AND [User] = ? AND " +
"Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery'," +
"'CA Review', '1TSI To Be Delivered');";
OleDbCommand dbcommand = new OleDbCommand(query, conn);
dbcommand.Parameters.AddWithValue("#p1", curTime.AddHours(-1));
dbcommand.Parameters.AddWithValue("#p2", User);
dbcommand.Connection.Open();
dbcommand.CommandType = CommandType.Text;
OrdersPerHour = (int)dbcommand.ExecuteScalar();
In this way the burden to correctly interpret your value is passed to the Framework code that could format dates, decimals and strings according to your database requirements. By the way this will also prevent Sql Injection
Also, the word USER is a reserved keyword in Access SQL and thus you need to encapsulate it with square brackets
First and most important: Use Parametrized Queries!
Regarding your problem, I suggest you to debug the code:
Get the Commandtext of your "OleDbCommand dbcommand" and manually query to see if you get the same result.
Also, you should put your code within the try catch block, else it does not make sense at all.

Categories

Resources