In my program, i implemented a simple database search that takes in a string (name or part of the name) and returns the corresponding details:
string nameSearch = textBox1.Text;
DataRow[] resultRows;
resultRows = ds1.Tables["Lecturers"].Select("Name='" + nameSearch + "'");
But i'm not getting the expected results unless i type in the ENTIRE NAME correctly. How can i modify the 'Select()' to get results when i input only a part of the name?
You can try using a RowFilter as in the below example:
ds1.Tables["Lecturers"].DefaultView.RowFilter = "[Name] LIKE '"+ nameSearch +"'";
DataTable dtOutput = ds1.Tables["Lecturers"].DefaultView.ToTable();
A quick check of DataTable.Select on MSDN leads you to DataColumn.Expression...
resultRows = ds1.Tables["Lecturers"].Select("Name like '%" + nameSearch + "&'");
use Name LIKE '% + namesearch + '%
Try this?:
resultRows = ds1.Tables["Lecturers"].Select("Name like '%" + nameSearch + "%'");
I'm assuming this is not 'production' code. Looks like a big sql injection here.
Related
first sry for my bad title
i have prblem for loading field name form access database because my field name in access table is="نام خانوادگی"
so when i use this query :
DataView dvtell = dtTell.DefaultView;
dvtell.RowFilter = "نام خانوادگی LIKE '%" + textBox6.Text + "%'";
return error because between نام and خانوداگی is a space .
but when i use query without 'space' // my code working good .
any suggestion ? how can i use this 'نام خانوادگی' field name in my code ?
i have 5 field name with space and i cant use it .
Try using square brackets, like this:
dvtell.RowFilter = "[نام خانوادگی] LIKE '%" + textBox6.Text + "%'";
I need to use the following query in my C# code:
SELECT AVG(Percent)
From Table1
Where code Like "Sport" and Year Like"2011" and Sitting Like"June";
I did it like this:
"SELECT AVG(Percentage) FROM MasterTable WHERE Code LIKE " + comboBoxSubject.Text +
"AND Year LIKE "+dateTimePicker1 +" AND Sitting LIKE June"
but i get an exception probably because the parameters are extracted from different controls and are not placed in inverted commas.
Can anyone help me ?
ANSWER
That is the query that worked for me:
"SELECT AVG(Percent) FROM MasterTable WHERE Code LIKE '" + comboBoxSubject.Text + "' AND Year LIKE '" + dateTimePicker1.Value.Year + "' AND Sitting LIKE 'June'"
Supposing you use SQLite, because you don't mention any database. This is how you can avoid SQL injection.
var selectCommand = new SQLiteCommand("#SELECT AVG (PERCENT)
FROM TABLE1
WHERE CODE LIKE #sport AND YEAR LIKE #year AND SITTING LIKE #month");
selectCommand.Parameters.AddWithValue("#sport", sportParameter);
selectCommand.Parameters.AddWithValue("#year", yearParameter);
selectCommand.Parameters.AddWithValue("#month", monthParameter);
There are three problems.
There's no space after the code value and AND
There are missing single quotes between values
The wildcard symbol (%) is missing from the SQL LIKE statements
It depends what kind of project you are working on but often I find it is much easier to spot syntax errors and missing spaces by printing the end query out. For example, below is a console application that does this.
static void Main(string[] args)
{
const string code = "Sport";
const string year = "2011";
Console.WriteLine("SELECT AVG(Percentage) FROM MasterTable WHERE Code LIKE '%" + code + "%' AND Year LIKE '%" + year + "%' AND Sitting LIKE '%June%'");
}
Use single quotes for character fields.
"SELECT AVG(Percentage) FROM MasterTable WHERE Code LIKE '" + comboBoxSubject.Text +
"' AND Year LIKE '" + dateTimePicker1 + "' AND Sitting LIKE 'June'"
Use % and ' and please consider to use parameters:
SELECT AVG(Percentage) FROM MasterTable WHERE (Code LIKE '%' + #text + '%')
MySqlCommand cmd = new MySqlCommand("SELECT Employee_No, Image, Last_Name, First_Name, Middle_Name, Suffix, Sex, Birthdate, Contact_No, Address, Username FROM user_tbl WHERE Employee_No LIKE '%" + searchemployeeno + "%' OR Last_Name LIKE '%" + searchemployeeno + "%' ", SQLConn.conn);
I have been following this site for basic Access database implementation in C#
http://www.homeandlearn.co.uk/csharp/csharp_s12p12.html
I want to search more than one row. This code works for one row.
string searchFor = txtFurniture.Text;
returnedRows = ds1.Tables["Furniture"].Select("Finish='" + searchFor + "'");
How do I add in additional rows to check? I have tried something like
returnedRows = ds1.Tables["Furniture"].Select("Finish='" + "Style='" + searchFor + "'");
but this fails.
you need to add and condition
returnedRows = ds1.Tables["Furniture"].Select("Finish='" + searchFor +
"' and Style='" + searchFor + "'");
In addition you can check this answer might help you to understand easily : Datatable select with multiple conditions
You mean an additional field to check.
Make a condition that looks like this:
Finish='something' and Style='something'
using:
returnedRows = ds1.Tables["Furniture"].Select("Finish='" + searchFor + "' and Style='" + searchFor + "'");
As referenced in the documentation for the DataTable.Select method, the documentation for the DataColumn.Expression property describes the syntax to be used with the filterExpression parameter. In your case, use And to create a compound expression with your two conditions:
returnedRows = ds1.Tables["Furniture"].Select("Finish='" + searchFor + "' And Style='" + searchFor2 + "'");
...or more readably...
string filterExpression = string.Format("Finish='{0}' And Style='{1}'", searchFor, searchFor2);
DataRow[] returnedRows = ds1.Tables["Furniture"].Select(filterExpression);
When i use this string as a sql command-string compiler gives me no error:
string sql = "SELECT * FROM Students WHERE StudentNo='" + T_No.Text + "'";
But, if i use this string (includes '%' character) it says "Error converting data type varchar to bigint":
string sql = "SELECT * FROM Students WHERE StudentNo='%" + T_No.Text + "%'";
What should i change in order to use '%' in my statement?
string sql = "SELECT * FROM Students WHERE convert(nvarchar,StudentNo) LIKE '%" + T_No.Text + "%'";
Note, however, that this is inefficient.
Take a look at the following page.
http://web.archive.org/web/20150519072547/http://sqlserver2000.databases.aspfaq.com:80/how-do-i-search-for-special-characters-e-g-in-sql-server.html
The % sign has a special meaning in SQL.
string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE (users.ID= " + a.ToString() + ") AND (obroki_save.datum= #datum)";
using (OleDbCommand cmd = new OleDbCommand(queryString,database))
{
DateTime datum = DateTime.Today;
cmd.Parameters.AddWithValue("#datum", datum);
}
loadDataGrid2(queryString);
I tried now with parameters. But i don't really know how to do it correctly. I tried like this, but the parameter datum doesn't get any value(according to c#).
please try this :
database = new OleDbConnection(connectionString);
database.Open();
date = DateTime.Now.ToShortDateString();
string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE users.ID= " + a.ToString()+" AND obroki_save.datum= '" +DateTime.Today.ToShortDateString() + "'";
loadDataGrid2(queryString);
when you use with Date, you must write like this
select * from table where date = '#date'
not like
select * from table where date = #date
While it's usually useful to post the error, I'd hazard a guess and say that you're getting a conversion error with your date.
You should really look at parameterising your queries...
You should read this: http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/
And if you can't be bothered reading that, then try changing your 'a' variable to '1; DROP TABLE obroki; --' (but only after you back up your database).
Perhaps you need to write your SQL string in the SQL dialect of the database you're using. In Jet/ACE SQL (what's used by Access), the delimiter for date values is #, so you'd need this:
obroki_save.datum= #" +DateTime.Today.ToShortDateString() + "#"
Of course, some data interface libraries translate these things for you, so that may not be the problem here.