Use of commercial #AT when dealing with data access in ASP.Net? - c#

Two small issues, mostly concerning the #AT syntax when dealing with data in ASP.Net (C#). Most online tutorials show a lot of this following type of code but fail to mention (or I may have overlooked) the actual purpose of the ampersand although they do explain the general purpose of the code. In this example, just querying the database to get data pertaining to a certain month for a calender control.
protected DataSet GetCurrentMonthData(DateTime firstDate,
DateTime lastDate)
{
DataSet dsMonth = new DataSet();
ConnectionStringSettings cs;
cs = ConfigurationManager.ConnectionStrings["ConnectionString1"];
String connString = cs.ConnectionString;
SqlConnection dbConnection = new SqlConnection(connString);
String query;
query = "SELECT HolidayDate FROM Holidays " + _
" WHERE HolidayDate >= #firstDate AND HolidayDate < #lastDate";
SqlCommand dbCommand = new SqlCommand(query, dbConnection);
dbCommand.Parameters.Add(new SqlParameter("#firstDate",
firstDate));
dbCommand.Parameters.Add(new SqlParameter("#lastDate", lastDate));
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(dbCommand);
try
{
sqlDataAdapter.Fill(dsMonth);
}
catch {}
return dsMonth;
}
First issue: What do #firstDate and #lastDate mean or reference in the database string query? Is that referencing the parameters being passed in GetCurrentMonthData method or the actual column name in the database table ?
query = "SELECT HolidayDate FROM Holidays " + _
" WHERE HolidayDate >= #firstDate AND HolidayDate < #lastDate";
Second issue: What is the difference between #firstDate and firstDate? Am I correct in saying firstDate is the actual parameter variable itself?
dbCommand.Parameters.Add(new SqlParameter("#firstDate",
firstDate));

I agree with #har07. That is not a ampersand. An ampersand, as far as I know, looks like this -> &. To answer the question, the 'at' sign (#) is used to indicate variables in a parameterized query in c#.
In the code
dbCommand.Parameters.Add(new SqlParameter("#firstDate",firstDate));
you are assigning the value of the DateTime variable firstDate to the #firstDate variable in your query.
Here's an example that's a bit less confusing(I hope):
Let's say I have a string variable called myName and I want to pass that to my query select * from students where name = #name.
To pass the value of myName to #name in my query, I would do
dbCommand.Parameters.Add(new SqlParameter("#name",myName));
I hope that helps.

Your First Question :
According to the documentation, the name must start with an #:
The ParameterName is specified in the form #paramname.
More Information :
Is it necessary to add a # in front of an SqlParameter name?
Second Question :

First, that isn't ampersand but at sign or commercial at. It is used in this particular context to indicates an SQL parameter name.
And this part showing how you pass the actual value (contained in the firstDate C# variable) to the SQL parameter (#firstDate) :
dbCommand.Parameters.Add(new SqlParameter("#firstDate",
firstDate));
You can read your parameterized SQL query statement like string concatenation but with big advantages (the former save you from SQL injection, arbitrary data type to string conversion with correct formatting*, etc) :
query = "SELECT HolidayDate FROM Holidays " + _
" WHERE HolidayDate >= " + firstDate + " AND HolidayDate < " + lastDate;
*) See that in the string concatenation version above you need to convert firstDate and lastDate to string with correct format according to your RDBMS local settings to make it work.

The main use of #inputvalue in query statement is to avoid sql injection attacks.
If you use normal concatenation method in building query statement, Hackers can easily bypass the statements with sql injection.
Eg:
"Select * from user where username ='" + username.text + "' and password ='" + password.text + "'"
If you use the above statement to validate the user login, think what will happen if the user types a' = 'a') or 'sometext in username textbox and sometext in password box. It will returns more than one record on execution and enters into account area, if you checks with no of return records in user validation.
To avoid this, Microsoft introduced #parameter to build sql query statements. Whatever value you pass in the #parameter is considered as input parameter value and you can't inject sql statements in it.
Answer for your second question
dbCommand.Parameters.Add(new SqlParameter("#firstDate",
firstDate));
The above method is used to replace the #parameter(first argument in Add method) with parameter value(second argument in Add method). It uses # as the delimiter. it checks if there is a word with prefix '#' in query statement, it will be marked as a parameter and it is replaced by the actual value which is passed as the second argument in the Add method.

Related

MySQL Query Returns Parameter Column Name [duplicate]

This question already has answers here:
How to pass a table as parameter to MySqlCommand?
(2 answers)
Closed 6 years ago.
I am working in C# and MySQl in VS2015 to query my database and return a the information in a VARCHAR type column titled "method". However, the query returns the string "method", and not the values of the method column.
below is the code:
string queryOne = "SELECT " + "#columnName" + " FROM log.transactions";
MySqlCommand cmdOne = new MySqlCommand(queryOne, connectionString);
cmdOne.Parameters.AddWithValue("#columnName", "method");
MySqlDataReader dataReaderOne = cmdOne.ExecuteReader();
while (dataReaderOne.Read())
{
Console.WriteLine(dataReaderOne.GetString(0));
}
dataReaderOne.Close();
While this is the output:
method
method
method
.
.
.
.. for the number of rows in the method column. Is this a formatting problem? Is it possible that the configuration of my database is preventing VarChar's from returning correctly? When I change the query to query a column of type INT, it returns the correct values for an INT type column.
You can't parameterize a column name in a select statment. What you're doing is exaclty like saying select 'foo' from log.transactions. It selects the string 'foo' once for each row. You're just sticking a string value in there; it's not parsing the string value as SQL.
What you can do (if you can afford it) is select * from log.transactions, then your C# code can grab the data in whatever column the caller passed you the name of. With a lot of rows you could be dragging a lot of useless junk back from the DB though.
What you want in the code you show, though is just this:
string queryOne = "SELECT method FROM log.transactions";
If you really want to parameterize "method", that's sketchy because of SQL injection vulnerabilities.
string queryOne = "SELECT " + fieldname + " FROM log.transactions";
That looks good until some comedian using your application gives you a value of "0; drop table log.transactions;--" in the textbox. Then you've got troubles. If you ever concatenate a string variable into a SQL string that you're going to execute, you've got to be fanatical about sanitizing it, and even then you want to avoid it any way you can. It's Russian roulette.
Your query formation has to be like if you want to keep your column dynamic.Now pass column name accordingly.
string queryOne = "SELECT " + column_name + " FROM log.transactions";
MySqlCommand cmdOne = new MySqlCommand(queryOne, connectionString);
MySqlDataReader dataReaderOne = cmdOne.ExecuteReader();
while (dataReaderOne.Read())
{
Console.WriteLine(dataReaderOne[column_name]);
}
dataReaderOne.Close();

Data is Null. This method or property cannot be called on Null value (mysql to textbox)

My friend wants to transfer her data from the database to a textbox to her program in c# but it gets an error of this:
"Data is Null. This method or property cannot be called on Null
values."
Here is the code by the way:
sql_command = new MySqlCommand("select sum(lt_min_hours) as TotalLate from tbl_late where (late_date between '" + date_start + "' and '" + date_to + "' and empid = '" + empid + "')", sql_connect);
sql_reader = sql_command.ExecuteReader();
if (sql_reader.Read())
{
textBox_tlate.Text = sql_reader.GetString("TotalLate");
}
else
{
MessageBox.Show("No Data.");
}
From documentation;
SUM() returns NULL if there were no matching rows.
But first of all, You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
After that, you can use ExecuteScalar instead of ExecuteReader which is returns only one column with one row. In your case, this is exactly what you want.
textBox_tlate.Text = sql_command.ExecuteScalar().ToString();
Also use using statement to dispose your connection and command automatically.
You need to test for DbNull.Value against your field before assigning it to the textbox
if (sql_reader.Read())
{
if(!sql_reader.IsDbNull(sql_reader.GetOrdinal("TotalLate")))
textBox_tlate.Text = sql_reader.GetString("TotalLate");
}
EDIT
According to your comment, nothing happens, so the WHERE condition fails to retrieve any record and the result is a NULL.
Looking at your query I suppose that your variables containing dates are converted to a string in an invalid format. This could be fixed using a ToString and a proper format string (IE: yyyy-MM-dd) but the correct way to handle this is through a parameterized query
sql_command = new MySqlCommand(#"select sum(lt_min_hours) as TotalLate
from tbl_late
where (late_date between #init and #end and empid = #id", sql_connect);
sql_command.Parameters.Add("#init", MySqlDbType.Date).Value = date_start;
sql_command.Parameters.Add("#end", MySqlDbType.Date).Value = date_end;
sql_command.Parameters.Add("#id", MySqlDbType.Int32).Value = empid;
sql_reader = sql_command.ExecuteReader();
This assumes that date_start and date_end are DateTime variables and empid is an integer one. In this way, the parsing of the parameters is done by the MySql engine that knows how to handle a DateTime variable. Instead your code uses the automatic conversion made by the Net Framework that, by default, uses your locale settings to convert a date to a string.

Multiple usage of a parameter in a SQLCommand C#

I need to ask something again. I'm a PHP developer for two years. Previously, I got my hands with Java for a year and C# for at least some couple of months before Java. I'm in the process of relearning C#. The following C# string declaration is from a tested SQL script that determines if a reservation entry (from the [RESERVATION] table) overlaps with an existing Pending reservation (filtered by the [status] as [r] where clause)
string query = "select [r].[id], [first_name], [middle_name], [surname], [extension], [reservation_time_from], [reservation_time_to] " +
"from [RESERVATION] as [r] " +
"join [CUSTOMER] as [c] on [r].[customer_id] = [c].[id] " +
"where [reservation_date] = #reservation_date and " +
"( #reservation_time_from between [reservation_time_from] and [reservation_time_to] or " +
"#reservation_time_to between [reservation_time_from] and [reservation_time_to] " +
") or " +
"( [reservation_time_from] between #reservation_time_from and #reservation_time_to " +
"or [reservation_time_to] between #reservation_time_from and #reservation_time_to " +
") and " +
"[status] = 'Pending' " +
"order by [transaction_date] asc";
I attached the parameters using this method:
command.Parameters.AddWithValue();
Now when I perform the query using the command.ExecuteReader(), it seems that the query does not fetch overlap schedules of [RESERVATION]. I got a hunch that it has something to do with the source of the data: that is a DateTimePicker object; since the column type of the columns are date only, but I'm not quite sure. I attached the values of those time picker using this code (that is a parameter for a time column):
command.Parameters.AddWithValue("#reservation_time_from", SqlDbType.Date).Value = ((DateTime)param[value]).TimeOfDay;
Can someone assist me? Note though that some parameters (such as #reservation_time_from) occurred at least twice on the query string. Thanks for the support.
EDIT:
These is how I attached parameters (sorry the previous example is wrongly pasted, Tee hee):
command.Parameters.AddWithValue("#reservation_time_from", SqlDbType.Time).Value = ((DateTime)param['reservation_time_from']).TimeOfDay;
command.Parameters.AddWithValue("#reservation_time_to", SqlDbType.Time).Value = ((DateTime)param['reservation_time_to']).TimeOfDay;
command.Parameters.AddWithValue("#reservation_date_from", SqlDbType.Date).Value = ((DateTime)param['reservation_date_from']).Date;
command.Parameters.AddWithValue("#reservation_date_to", SqlDbType.Date).Value = ((DateTime)param['reservation_date_to']).Date;
AddWithValue takes the value as the second parameter, and so is interpreting the SqlDbType as the parameter value. You will need to use Add instead of AddWithValue:
command.Parameters.Add("#reservation_time_from", SqlDbType.Time)
.Value = ((DateTime)param[value]).TimeOfDay;
From the documentation:
AddWithValue replaces the SqlParameterCollection.Add method that takes
a String and an Object. The overload of Add that takes a string and an
object was deprecated because of possible ambiguity with the
SqlParameterCollection.Add overload that takes a String and a
SqlDbType enumeration value where passing an integer with the string
could be interpreted as being either the parameter value or the
corresponding SqlDbType value.
Edit: what you're doing only works because the SqlCommand is correctly assigning the SqlDbType based on the value provided in the Value set and the SqlDbType is irrelevant: run this code to see:
var cmd = new SqlCommand();
var param = cmd.Parameters.AddWithValue("#date_from", SqlDbType.Date);
Console.WriteLine(param.ParameterName);
Console.WriteLine(param.SqlDbType);
Console.WriteLine(param.Value.GetType());
Console.WriteLine();
param.Value = DateTime.Today;
Console.WriteLine(param.ParameterName);
Console.WriteLine(param.SqlDbType);
Console.WriteLine(param.Value.GetType());
This outputs:
#date_from
Int
System.Data.SqlDbType
#date_from
DateTime
System.DateTime
Sorry my bad, it seems that I've slightly overlooked the mapping of sql type on some of the parameters:
command.Parameters.AddWithValue("#reservation_date_from", SqlDbType.Date).Value = ((DateTime)param['reservation_date_from']).Date;
command.Parameters.AddWithValue("#reservation_date_to", SqlDbType.Date).Value = ((DateTime)param['reservation_date_to']).Date;
Instead of using SqlDbType.Date, I must use SqlDbType.DateTime. I overlooked that the sql type of the columns [reservation_date_from] and [reservation_date_to] are both DateTime. Now the overlap trap works like a charm. Sorry for the silly mistake...

Problems with saving data with single quote ' in the query [duplicate]

This question already has answers here:
Single and double quotes in Sql Server 2005 insert query
(3 answers)
Closed 8 years ago.
I have an asp.net project in which I am getting an error while saving data.I have a text box for school name, most school names get saved but if I have a school name like St.Xavier's, it creates a problem during the execution of the insert query.This happens due to the presence of a single quote in the text.As a result the eventual query that I get is:
Insert Into tblSchool(SchoolName, CreatedBy, CreatedOn)
values('St.Xavier's',1,'2014-6-13 13:14:16')
How can I save data with single quotes in the text? I am using Microsoft SQL Server 2005.
You haven't shown your code, but I strongly suspect that you've got code such as:
// Bad code!
String sql = "Insert Into tblSchool(SchoolName, CreatedBy, CreatedOn) "
+ "values('" + name + "'," + creator + ",'" + date +"')";
Don't do that. It's hard to read, error-prone in terms of conversions, and vulnerable to SQL Injection attacks.
Instead, you should use parameterized SQL. Something like:
String sql = "Insert Into tblSchool(SchoolName, CreatedBy, CreatedOn) "
+ "values(#Name, #CreatedBy, #CreatedOn)";
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#Name", SqlDbType.VarChar).Value = name;
command.Parameters.Add("#CreatedBy", SqlDbType.Int).Value = creator;
command.Parameters.Add("#CreatedOn", SqlDbType.DateTime).Value = date;
int results = command.ExecuteNonQuery();
...
}
See the SqlCommand.Parameters documentation for more details.
You need to work with bind parameters in your SqlCommand. Anything else is bound to fail.
You need to quote the ' with another '. I.e.:
values('St.Xavier''s',1,'2014-6-13 13:14:16')

Data type mismatch in criteria expression | Access, OleDb, C#

I read/update data from MS Access using C#.
My code is:
public static void UpdateLastLogin(int userid, DateTime logintime) ///logintime = DateTime.Now
{
string sql = #"UPDATE [Customers] SET [LastLogin]=?";
OleDbParameter[] prms = new OleDbParameter[] {
new OleDbParameter("#LastLogin",logintime)
};
using (DAL dal = new DAL())
{
dal.UpdateRow(sql, false, prms);
}
}
When it comes to Dates, I having trouble.
This throws a "Data type mismatch in criteria expression." error.
(I removed WHERE clause for keeping it simpler)
Am I suuposed to enclose [LastLogin]=? question mark with single quotes, # signs .. does not help.
Any leads on how to handle DateTime objects with Access and OleDb provider will be greatly appreciated.
Thanks in advance.
There is a known issue with OleDb and dates. Try doing something like:
OleDbParameter p = parameter as OleDbParameter;
if (null == p)
parameter.DbType = DbType.DateTime;
else
p.OleDbType = OleDbType.Date;
Or use explicit format string:
value.ToString("yyyy-MM-dd hh:mm:ss")
I solved this using the following code
OleDbCommand cmd = new OleDbCommand(qry, cnn);
cmd.Parameters.Add("datenow", OleDbType.Date);
cmd.Parameters["datenow"].Value = DateTime.Now;
Firstly, no your SQL statement should be:
"UPDATE Customers SET LastLogin=#LastLogin"
Secondly, the reason you are receiving the date mismatch error will probably be your passing '?' as your date time into the LastLogin field instead of the actual logintime parameter.
maybe try
DateTime.Now.ToShortDateString() + ' ' + DateTime.Now.ToShortTimeString()
instead, pass it as String (and maybe enclose with # then)
Should it not be
"UPDATE Customers SET LastLogin='#LastLogin'"
And #LastLogin should be
logintime.ToString("yyyy-MM-dd hh:mm:ss")
edit
Could you not just inline the whole thing?
"UPDATE Customers SET LastLogin='" + logintime.ToString("yyyy-MM-dd hh:mm:ss") + "'"
Try setting the "DBTYPE" property of the parameter to identify it as a date, datetime or datetime2 as appropriate...
prms[0].DbType = DbType.DateTime;
There are 7 signatures to the new OleDbParameter() call, so you may change the signature instance, or just do explicitly as I sampled above since you only had 1 parameter in this case.

Categories

Resources