tags:

views:

101

answers:

3

i`m doing

string sql = "select * from publisher where title like "'"+tbproperty.text+";

but it`s not working!

regards..

A: 

Correction..

string sql = "select * from publisher where title like '" + tbproperty.text + "'";
this. __curious_geek
hey listen.. i have my function in my class but the tbproperty does not show in my class.. ?? how do i do it ??
Azka
Please put your code here, so that we can analyze and check.
this. __curious_geek
@Azka - only you know where `tbproperty` exists; if you are doing your data access separate to the UI (which you should) then you'll have to pass the desired title in as a parameter to your method.
Marc Gravell
i have my search publisher function in my class publisher and it is :public int searchpublisher(){SqlCommand cmd = new SqlCommand("select * from publisher where title like @title");cmd.Parameters.AddWithValue("@title", but here in the object value, the tbproperty does not exist in the intellisence.. }
Azka
You can modify the metod in your Publisher class as follows:public int searchpublisher(string title) { SqlCommand cmd = new SqlCommand("select * from publisher where title like @title");cmd.Parameters.AddWithValue("@title", title);}Then call that method from the appropriate place in the UI (i.e. where you have access to the textbox) and call it like this:int publisher = searchpublisher(tbproperty.Text);
Anton
it aint working :( ..
Azka
+9  A: 

Use SqlParameter:

SqlCommand cmd = new SqlCommand("select * from publisher where title like @title");
cmd.Parameters.AddWithValue("@title", tbProperty.Text);

If you need to add more to the parameter, then do the following (E.g.: output parameter):

SqlParameter param = new SqlParameter("@param ", SqlDbType.NVarChar, 250) { Direction = ParameterDirection.Output };
cmd.Parameters.Add(param);

This means you don't need to build the string per se and stops SQL injection.

Kyle Rozendo
+1 wish I could +10000 your answer!! Always always always (and no exceptions) use parametrized queries.
marc_s
+4  A: 

With LIKE, if you expect begin/ends matches you need some wildcards such as '%', and I'm assuming that the user isn't adding those; but - important: don't concatenate user input. Ever; you want something like:

sql = "select * from publisher where title like @arg";

With @arg defined as a parameter, with value something like:

cmd.Parameters.AddWithValue("@arg", "%" + tbproperty.text + "%");
Marc Gravell