Click here to Skip to main content
16,019,018 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
in my tables I a have columns Name, Age, Date. The Date column datatype is date.
So I want to have a button that whenever I click it displays all the rows with the same Date value base on the value I choose to filter my datetimepicker.
It will display on the datagridview.

What I have tried:

in my event handler button :

con.open()

SqlDataAdapter sda = new SqlDataAdapter ("select * from mydb where Date = '"+datetimepicker1.value+"'", con);
DataTable tb = new DataTable();
sda.fill(dt);
mydatagridview.DataSource = dt;
con.Close();
Posted
Updated 14-Jun-18 21:37pm

1 solution

That will work, but it's a bad idea. Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

So even for values that can't be SQL Inject prone, you should use parameters - because in this case it prevents confusion, given that the database server and the app may be running on machines with very different culture settings, so the default string generated by your code may not match the date format that the database server machine is set for: if yours uses MM-dd-yy and the server uses dd-MM-yy then you will retrieve the wrong info.

If you aren't getting any data at all after you have fixed this throughout your whole app, then double check the data in your database and check that the Date column does not contain any time info (or that it's set to midnight) - an "equals comparison" needs the values to be identical down to the tick, not just to the day.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900