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);
Related
i am not getting what is the issue in the query probably i am not following the correct way to put the string and char sign , i am inserting the data in c# to local host with where clause please check the query and Error i am getting
Here is the query
String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '"+id+ ",s.session,'" + title.Text+",'"+ from.Value.Date.ToString("yyyy-MM-dd")+",'"+to.Value.Date.ToString("yyyy-MM-dd")+ ", c.class_name,'"+x+",'"+x+" from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";
Exception image
here the image for exception i am getting after run this query
On your ...'"+x+"... you forgot to close the single quotes. You open them but you never close them after you add the X variable to your query. All SQL is seeing is "'0," which is invalid syntax.
I recommend use SQLparameters to avoid sql injection but your error is you forgot to close the single quotes it shoud be like this '"+cls + "'
String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '" + id + "','"+s.session+"','" + title.Text + "','" + from.Value.Date.ToString("yyyy-MM-dd") + "','" + to.Value.Date.ToString("yyyy-MM-dd")+"' , '"+c.class_name+"','" + x + "','" + x + "' from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";
I don't know why you need that on select columns. and you provided insufficient information and code on your question.
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(near "=": syntax error (code 1): , while compiling: DELETE FROM notesWHEREid='1')
This is the error i am getting:
This is the part of my database handler that is the source of this error:
public void deleteNote(String id) {
SQLiteDatabase db = this.getWritableDatabase();
String deleteQuery="DELETE FROM " + DatabaseValues.TABLE_NOTES + "WHERE" + DatabaseValues.NOTES_ID + "= '" + id + "'";
db.execSQL(deleteQuery);
db.close();
}
If you are using C# 6.0, using interpolated strings makes life much easier for strings concatenation, avoiding such silly errors:
String deleteQuery= $"DELETE FROM {DatabaseValues.TABLE_NOTES} WHERE {DatabaseValues.NOTES_ID} = id";
Note: $ operator is available in C# 6.0. Also you should take a look into how to build parameterized queries because passing parameters like this can expose you to SQL injection.
Change your following statement:
String deleteQuery="DELETE FROM " + DatabaseValues.TABLE_NOTES + "WHERE" + DatabaseValues.NOTES_ID + "= '" + id + "'";
to
String deleteQuery= "DELETE FROM " + DatabaseValues.TABLE_NOTES + " WHERE " + DatabaseValues.NOTES_ID + " = '" + id + "'";
Actually you are combining the table name with where clause. You need to add a space before and after WHERE Clause like " Where "
Hope it helps.
I'm looking a way to convert this query:
Select *
From Tasks
Where Addresses_Street1+' '+Addresses_Street2+' '+Addresses_City +' '+Addresses_ZipCode Like '%'+replace(ltrim(rtrim('Leon Deladriere 15')),' ','%')
to a Linq C# expression.
I know that Contains() and Trim() can be use for the method but how to handle the replace ' ' by '%' ?
This expression is used to provide to user one single input with an address and look into multiples columns to find a matching one.
I use Linqpad but I doesn't see equivalent in Linq
You can try.
(from r in Tasks where SqlMethods.Like(
r.Addresses_Street1 + " " +
r.Addresses_Street2 + " " +
r.Addresses_City + " " +
r.Addresses_ZipCode,
"%Leon Deladriere 15".Trim().Replace(" " , "%"))
select r)
Note, LinqSql is smart enough to know that it can do the Trim and Replace locally rather than asking Sql to do it.
However if you use a field rather than a constant, eg
(from r in Task where SqlMethods.Like( ... ,
r.Addresses_Street1 + " " +
r.Addresses_Street2 + " " +
r.Addresses_City + " " +
r.Addresses_ZipCode,
r.AnotherField.Trim().Replace(" " , "%"))
select r)
then this will ask sql to do the trim and replace.
Try this:
var user = "Leon Deladriere 15".Trim();
Tasks.Where(t => (t.Addresses_Street1 + t.Addresses_Street2 + t.Addresses_City + t.Addresses_ZipCode).Contains(user));
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.
i am updating a sql server 2008 database using c# like this:
foreach (DataRow row in dt.Rows)
{
faxstatus = row.ItemArray[5].ToString().Contains("0000") ? "Faxed" : "Error";
query =
#"update FileLog set
FaxStatus=" + "'" + faxstatus + "'," +
"FaxedPageCount=" + "'" + row.ItemArray[1] + "'," +
"dtFaxed=" + "'" + row.ItemArray[2] + "'," +
"BiscomCode=" + "'" + row.ItemArray[5] + "', " +
"RetryCount=" + "'" + row.ItemArray[4] + "' " +
"where CONVERT(VARCHAR(255), JobID) =" + "'" + row.ItemArray[3] + "'" +
" and FaxStatus<>'Faxed'";
command = new SqlCommand(query, myConnection);
command.ExecuteNonQuery();
NumberOfRecordsUpdated++;
}
i would like to know whether it is possible to return how many records were updated?
Yes. Use ExecuteNonQuery's return value. :-)
Quoting ExecuteNonQuery's documentation:
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command.
Capture and use the result of ExecuteNonQuery to an integer. That method returns the number of records affected by the operation.
See SqlCommand.ExecuteNonQuery Method.
That being said, how much do you trust your datasource? Enough to bet your data integrity on it? I'd be remissed if I didn't implore you to explore parameterized queries. A using statement would also be warranted so that your disposable resources (SqlConnection, SqlCommand, etc.) are properly dealt with.
Append SELECT ##ROWCOUNT to your statement and use ExecuteScalar instead of ExecuteNoneQuery.
Refering to SqlCommand.ExecuteNonQuery Method :
Return Value
Type: System.Int32
The number of rows affected.
You could use ##ROWCOUNT .