|
-
Apr 15th, 2007, 06:34 AM
#1
Thread Starter
Lively Member
[RESOLVED] using Like in sql statement in C#
Hi,
Im passing a sql query using Like. It works fine when I run in Access.
But when I try to run it thru C# it does not retrieve any data into the datatable. So its something to do on the c# end and not the database.
this is my code:
Code:
string strSql = "Select * from tablename where timefield Like '* + s2 + "*'";
timefield is of datetime datatype.
s2 is a string value that has something like 9:45.
What could be the problem??
-
Apr 15th, 2007, 06:58 AM
#2
Re: using Like in sql statement in C#
That's not valid C# code but I'm guessing that that's a typo. Use "%" and "_" as multi-character and single character wildcards in SQL, not the Windows wildcards "*" and "?".
-
Apr 15th, 2007, 07:00 AM
#3
Re: using Like in sql statement in C#
You've got the quote characters mixed up.
In any case, you should not be embedding variables in a query like that. You should use parameterised queries:
Code:
SqlCommand mycommand = new SqlCommand("select * from tablename where timefield like @s2");
mycommand.Parameters.Add("@s2", s2);
SqlDataReader results = mycommand.ExecuteReader()
-
Apr 15th, 2007, 07:10 AM
#4
Thread Starter
Lively Member
Re: using Like in sql statement in C#
Hi guys,
thanks for your input. As Jmcilhinney wrote * should be replaced with % as shown below.
Code:
string sSQL = "Select * from tablename where datefield Like '%" + s2 + "%'";
I was passing the sql statment string to a method in another class. Thats why I didnt use parameters
-
Apr 15th, 2007, 08:30 AM
#5
Re: [RESOLVED] using Like in sql statement in C#
Then you should restructure your code so that you can pass parameters. Instead of passing a string to this other method you should pass a string and an array of parameters. It is just plain bad to use string concatenation to build SQL statements except in the rare cases where it's necessary. Those cases are where the values you're inserting are identifiers rather than values. In those cases you need to validate stringently to avoid SQL injection attacks.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|