tags:

views:

268

answers:

4

I am trying to set up a query for my dataset in C# using a variable for the filter. For example I am trying to only display a specific account number and his balance, with a local variable being the account number used as a filter for that exact one. Am I going about this the wrong way?

I am in no stretch of the imagination a real programmer, I am in a bind and have skimmed along using a guide to programming in C# and the limited brain power I have (which is now running on empty) :)

I also would like to alter the database information using a button with an eventhandler to add specific amounts a cell that was queried. Am I doomed for my lack of knowledge on hard coding or can I actually pull this off?

Sincerely, noobish engineer trying to program... or Jev

A: 

You could just use the variable to generate your SQL-Query dynamically, but beware of SQL-Injection - be really sure, that your variable may not contain SQL-Statements.

You could use a function, that builds and returns your SQL-Query like this, with the variable for the filter as parameter:

internal string BuildSQLQueryForAccount(int account)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("SELECT * ");
    sb.Append("FROM Accounts ");
    sb.AppendFormat("WHERE AccountNumber = {0}", account);
    return sb.ToString();
}
BeowulfOF
Bad idea, simply on principle. Why take the risk of the code being copied and used for a string parameter, leading to SQL injection? Parameterised SQL isn't hard, and it's worth using it ubiquitously (except for the *very* few places where you can't, such as parameterising the table names).
Jon Skeet
Well, I added the hint for SQL-Injection, so why the downvote?
BeowulfOF
Because it's giving a bad example which can easily be copy-pasted when SQL parameterisation is a much, much better solution.
Jon Skeet
+3  A: 

When you setup your dataset query you can do something like this;

SELECT Name FROM TableNames WHERE Name = @Variable

Have a look at this link for more info

It might be worth having a look into SQL injection attack too, click here

Dominic
+2  A: 
SqlCommand cmd = new sqlCommand("select * from table1 where column1 = @value", connection);
cmd.parameters.add(new SqlParameters("@value", "yourvalue"));
SqlDataReader dr = cmd.ExecuteReader();
while (dr.read())
{

   //code here!

}

I Hope this will be usefull!

Bigballs
You might want to edit your answer to format the code portion as code so that it is easier to read.
Andy
A: 

Once upon a time, I've written a little article on why you should definitely use parameters in SQL statements. (I've written it in response to the fact that I saw way to many people using string concat enation to write their queries).

You can find it here: http://fgheysels.blogspot.com/2005/12/avoiding-sql-injection-and-date.html

Frederik Gheysels