I am inserting data to a data list in asp.net. I need to modify the Select Command according to my needs. I did something like this,
string query = "SELECT [movieName], [sDate], [eDate], [IMDb], [imageUrl] FROM [movieDrama] WHERE ([category]='Drama' AND [movieName] like '%#key%') ORDER BY [movieName]";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#key", key);
SqlDataSource1.SelectCommand = query;
But this is not working. I think I did something wrong when defining '#key'. How to do it in correct way? Thanks in advance...
Use it like;
LIKE '%' + #key + '%'
instead of
LIKE '%#key%'
For full query;
string query = "SELECT [movieName], [sDate], [eDate], [IMDb], [imageUrl] FROM [movieDrama] WHERE ([category]='Drama' AND [movieName] LIKE '%' + #key + '%') ORDER BY [movieName]";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#key", key);
And actually, you don't need square brackets every column of your query, you just need to use when you want use some reserved keywords as a column names.
Just this:
string query = "SELECT [movieName], [sDate], [eDate], [IMDb], [imageUrl] FROM [movieDrama] WHERE ([category]='Drama' AND [movieName] like #key) ORDER BY [movieName]";
then
cmd.Parameters.AddWithValue("#key", "%"+ key + "%");
Try giving your sqlCommand the connection parameter:
SqlCommand cmd = new SqlCommand(query,YOURCONNECTIONSTRING);
cmd.Parameters.AddWithValue("key", key)
Related
I want to search all data in my DataGridView.
ID Name Effect
1 NameA Release
2 NameB Make Stronger
3 NameC Boost
In order to display proper data on DataGridView,
SqlCommand searchSqlCmmd;
SqlDataAdapter searchSqlAdpt;
DataTable searchDtbl = new DataTable();
searchSqlCmmd = new SqlCommand();
searchSqlCmmd.Connection = connection;
searchSqlCmmd.CommandType = CommandType.Text;
searchSqlCmmd.CommandText = "SELECT * FROM db.Ability WHERE Name = #searchText OR Effect = #searchText";
searchSqlCmmd.Parameters.Add("#searchText", TextBox.Text);
searchSqlAdpt = new SqlDataAdapter(searchSqlCmmd);
searchSqlAdpt.Fill(searchDtbl);
uxTable.DataSource = searchDtbl;
TextBox.Clear();
For query string, I used OR that I think it will search both columns. However, it only searches first column(NAME). Is my query string (CommandText) wrong?
use this:
SELECT * FROM db.Ability WHERE Name LIKE '%' + #searchText + '%' OR Effect = '%' + #searchText + '%'
I think you're looking for something more like:
"SELECT * FROM db.Ability WHERE Name LIKE %#searchText% OR Effect LIKE %#searchText%";
EDIT:
You would want to use something like below
SELECT Name, Effect FROM datainfo
WHERE Name LIKE '%Delta%' OR Effect LIKE '%Delta%';
http://sqlfiddle.com/#!9/c30bc5/3
I am creating a search bar and I am having a hard time constructing the correct query for that. Here is my code:
SqlCommand command1 = new SqlCommand(
"Select * from tbl_customer where customer_name like '%''"+ textBox1.Text +"''%' ",
MySqlConnection);
SqlCommand command1 = new SqlCommand("Select * from tbl_customer where customer_name like #search_value", MySqlConnection);
command1.Parameters.AddWithValue("#search_value","%" + textBox1.Text + "%");
You are adding too many 's.
SqlCommand command1 = new SqlCommand(
"Select * from tbl_customer where customer_name like '%"+ textBox1.Text +"%' ",
MySqlConnection);
Note that I have removed the extra 's after the first % and before the last %.
However, you should be careful about SQL injection and use parameters instead of directly adding control values into your query.
SqlCommand command1 = new SqlCommand(
"Select * from table-name where column-name like '%"+ textboxid.Text +"%' ",
MySqlConnection);
If u making a sample program then ok it will work ,but if you are looking for a professional use software or website then don't go with this method . Check sql injection because here you are directly adding the control values in query
In my program i need to get value from the database , so using a texbox so that client type anything and i can search from database.
My code is
SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl where terminalId = " + textBox_cardNumber.Text;
the above is not my full code but here in my code i am using textbox_cardNumber ...
I want that in quotes ''
it should be like
Select distinct transactionName from dbo.tbl where terminalId = '0097'
So my question is how to get in quotes???
Use a parameterized query like this
SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl " +
"where terminalId = #id";
sqlCmd.Parameters.AddWithValue("#id", textBox_cardNumber.Text);
....
In this way you defer the job to recognize your data (the textbox text) as a string to the Framework code that knows how to correctly quote your value. Also you remove the possibilities of Sql Injection attacks
"'" + textBox_cardNumber.Text + "'";
I hope I understood you!
You can also try this, but this is not good practice, used always Parameter.
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl where terminalId = '" + textBox_cardNumber.Text +"'";
You can try this code:
SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl where terminalId = '"
+ textBox_cardNumber.Text+"'";
Instead of string concatenation, you can should use parameterized sql instead. Because this kind of codes are open for SQL Injection attacks.
SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "SELECT DISTINCT transactionName FROM dbo.tbl
WHERE terminalId = #terminalID";
sqlcmd.Parameters.AddWithValue("#terminalID", textBox_cardNumber.Text);
A side note, take a look at SQL Injection Attacks by Example
You need to make use of prepared statements in which you use parameters.
Otherwise, you need to add quotes around your input string, but it will leave you open for SQL injection
I am using VS2005 C# ASP.NET and SQL Server 2005.
I have a search function on my asp page and I feel that my SELECT query is vulnerable to SQL injection.
This is my current SELECT statement:
string LoggedInUser = (User.Identity.Name);
SqlDataSource1.SelectCommand = "SELECT * FROM [TABLE1] where [" + DropDownList1.Text + "] like '%" + searchTB.Text + "%' AND [empUser] LIKE '%"+LoggedInUser+"%'";
SqlDataSource1.DataBind();
*where searchTB is my search text box; DropDownList1 is my search category; and LoggedInUser is the username of the logged in user.
I have implemented parameter instead of concatenation in one of my INSERT statement:
string sql = string.Format("INSERT INTO [TABLE2] (Username) VALUES (#Username)");
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("Username", usernameTB.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
I would like to change my SELECT statement like my INSERT statement, using parameter instead. May I know how should I change it?
Thank you
You can add parameters to your selectcommand using
SqlDataSource s = new SqlDataSource();
s.SelectParameters.Add("paramName", "paramValue");
There are other parameter collections for delete, update and insert too.
s.DeleteParameters
s.UpdateParameters
s.InsertParameters
More Information:
MSDN: SqlDataSource.SelectParameters Property
Programmatically Using SqlDataSource
hope this helps
See Using Parameters with the SqlDataSource Control
And SqlDataSource.SelectParameters Property
You can specify SelectParameters Property for SqlDataSource to use parameterized SQL query
Write a method that gets the data sourse and use sql parameters for the query. Here is a good example how to add parameters in a command object
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ID", SqlDbType.Int);
command.Parameters["#ID"].Value = customerID;
I would use a method for the query so that I separate the Database Access from the UI functionality. Also, this allows to reuse the query.
It's not a straightforward task to dynamically specify a fieldname in query, so I'd suggest just doing switch/case validation for field name, like this:
switch (DropDownList1.Text)
{
case "ValidField1":
case "ValidField2":
...
break;
default:
throw new ArgumentException(...); // or prevent query execution with some other statement
}
SqlDataSource1.SelectCommand = "SELECT * FROM [TABLE1] where [" + DropDownList1.Text + "] like #value AND [empUser] LIKE #user";
SqlDataSource1.SelectParameters.Add("value", "%" + searchTB.Text + "%");
SqlDataSource1.SelectParameters.Add("user", "%"+LoggedInUser+"%");
SqlDataSource1.DataBind();
You can simply use a filter expression for the SQL datasource SQL Datasource filter expression
You can write your own select function method with object datasource/datatable
i`m doing
string sql = "select * from publisher where title like "'"+tbproperty.text+";
but it`s not working!
regards..
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.
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 + "%");
Correction..
string sql = "select * from publisher where title like '" + tbproperty.text + "'";