• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 282
  • Last Modified:

Using a string variable in place of 'constant' when doing a SQL query in C#

I have the following line:
daDataAdapter.SelectCommand.CommandText = "SELECT Title, Image WHERE Cast LIKE '%Adam Sandler%' FROM Movie";

This works, and returns a list of movie TITLE's which adam sandler stars in.  I want to make it general now, and use a STRING variable instead of a hard-coded constant.

eg:
String temp = "%Adam Sandler%"
 daDataAdapter.SelectCommand.CommandText = "SELECT Title, Image WHERE Cast LIKE temp FROM Movie";

When I try this though, the query no longer works.
How can I make this work?

Thanks,
0
twibblejaway
Asked:
twibblejaway
  • 2
  • 2
1 Solution
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
daDataAdapter.SelectCommand.CommandText = "SELECT Title, Image WHERE [Cast] LIKE ? FROM Movie";
 daDataAdapter.SelectCommand.Parameters.Add "tmp", "%Adam Sandler%"


change the parameter value, and the next time the selectcommand runs it will take it.
0
 
twibblejawayAuthor Commented:
You are saying I should make my code look like this:

daDataAdapter.SelectCommand.CommandText = "SELECT Title, Image WHERE [Cast] LIKE ? FROM Movie"; daDataAdapter.SelectCommand.Parameters.Add "tmp", "%Adam Sandler%";

Wont this still only work for Adam Sandler??
What exactly does the second line do?  What does the ? in the first line do?
0
 
Arthur_WoodCommented:
daDataAdapter.SelectCommand.CommandText = "SELECT Title, Image WHERE Cast LIKE '" +  temp + "' FROM Movie";

AW
0
 
twibblejawayAuthor Commented:
indeed.  That did it.

Thanks.
0
 
Arthur_WoodCommented:
glad to help.

AW
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now