DataSet coming as Empty - c#

I have a method called searchDB that search the database according to keyword typed by user.
I am storing the search results in DataSet. This method search in only one column.
public DataSet searchDB(string identifier)
{
DataSet dataSet = new DataSet();
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "SELECT [identifier] FROM [Category3] WHERE [identifier] LIKE '" + identifier + "*'";
//string sql = "SELECT [identifier] FROM [Category3]";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
dataAdapter.Fill(dataSet, "identifier");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
oleConn.Close();
}
if (dataSet.Tables[0].Rows.Count == 0)
{
return null;
}
else
return dataSet;
}
The variable "identifier" gets value from the textbox.
Suppose, when i pass "windows" as value for variable, it should return 1 row.
But when i put breakpoint, it is hitting the if condition
if (dataSet.Tables[0].Rows.Count == 0)
{
return null;
}
and returning 0 rows.
Can anyone point out my mistake.

You seem to be using the SQL LIKE wrong (unless your identifier column really ends with an asterisk):
SELECT [identifier] FROM [Category3] WHERE [identifier] LIKE '" + identifier + "*'
Like uses the % character for wildcard, instead of *, so try:
SELECT [identifier] FROM [Category3] WHERE [identifier] LIKE '" + identifier + "%'
Edit: I didn't see that the question concerns MS Access, but the answer holds true still. See the following SO question: Why does a LIKE query in Access not return any records?
The Access Database Engine (Jet, ACE, whatever) has two ANSI Query Modes which each use different wildcard > characters for LIKE:
ANSI-89 Query Mode uses *
ANSI-92 Query Mode uses %

The LIKE filter should use % instead of * like here:
LIKE '" + identifier + "%'

Related

Fetching data for particular Month and year

I tried Query(given below in code) But it is showing me this error
No value given for one or more required parameters.
but while debugging I am passing date as this
string monthYY = dateTimePickerMonth.Value.ToString("M-yy");
So what is the right format to check it ,how can I do it ?
Code for Query
public int GetDrID_MonthWise(string DrName,string monthYY,int refDrID)
{
int data = 0;
try
{
string sql = "Select d.DoctorID From Doctor_Master d where d.LastName + ' ' + d.FirstName = '" + DrName + "' AND Patient_registration.RegDate='" + monthYY + "' AND Patient_registration.DoctorID=" + refDrID;
cmd = new OleDbCommand(sql, acccon);
rs = cmd.ExecuteReader();
while (rs.Read())
{
data = Convert.ToInt32(rs[0]);
}
}
catch (Exception err)
{
MessageBox.Show(err.Message.ToString());
}
return data;
}
This piece of your SQL statement informs the db engine Doctor_Master is the data source:
From Doctor_Master d
However, the WHERE clause refers to 2 fields which are not present in Doctor_Master:
Patient_registration.RegDate
Patient_registration.DoctorID
I'm unsure what you actually need. My hunch is you should INNER JOIN those tables. But I think you should design and test the query in Access, leaving c# out of the picture until after you have the Access query working as you wish.
I'm not sure exactly how you are passing your parameters but you need to specify values for all three of your parameters listed
public int GetDrID_MonthWise(string DrName,string monthYY,int refDrID)

Searching database with date

In my windows form, i have one text box where users enters the date in the format 16/02/2013 to search for all the entries on that particular date.
In database i have one column which stores date in this format.16/02/2013 02:47:36 AM.
Can somebody advise me with sql query to extract all the entries from database for that particular date and put it on dataset.
I am using this but it is not working.
public DataSet OrderByDate(string date)
{
// string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Amrit\\Desktop\\Database.accdb ;Persist Security Info=False;";
DataSet dataSet = new DataSet();
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "SELECT Customer.[Title] + SPACE(2) + Customer.[Customer's Name] as CustomerName, Customer.[Customer's Ebayname], Customer.[Email Address], Customer.[Phone Number], Customer.[Address 1] + SPACE(2) +Customer.[Address 2] + SPACE(2) + Customer.[City] + SPACE(2) + Customer.[Post Code]+ SPACE(2) + Customer.[Country] as Address, Customer.[Item Purchased], Customer.[Purchased Date], Customer.[Total Price] FROM Customer WHERE [Purchased Date] LIKE '" + "'" + date + "%'";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
dataAdapter.Fill(dataSet, "Customer");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
oleConn.Close();
}
if (dataSet.Tables.Count <= 0)
return null;
else
return dataSet;
}
In datbase the datetime is stored as Date/Time format.
On the database side, if your datatype is date, you can simply do:
where yourdatefield = #dateIn
If it's a datetime, you do this:
where yourdatefield >= #dateIn
and yourdatefield < the day after #dateIn
Since you are using .net there are a couple of things you need to improve in your application code. First, convert the date string to a DateTime object. Second, convert all the user inputs to parameters.
You may or may not need to enclose the datetime in single quotes in the sql, I dont remember:
DateTime start = DateTime.Parse("16/02/2013").Date;
DateTime end = start.AddDays(1);
string sql = "Select * From Customer WHere PurchasedDate >= {0} and PurchasedDate < {1}";
sql = string.Format(sql, start, end);
Also, this is a quick and dirty method that I wrote up here. It should work, but you REALLY should paramaterize this query.
Passing date values in this way does not work, because default formatted date and time value in .NET is not recognized by your SQL engine.
To pass any data to your query, it is best to always use parameters. Add a parameter to you command string:
string sql = "SELECT * FROM Customer WHERE PurchaseDate = #pdate";
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, connection);
adapter.SelectCommand.Parameters.AddWithValue("pdate", date);
adapter.Fill(dataSet, "Customer");
#pdate in the command text is a parameter. Values for the parameter must be supplied before executing the command, as you see in the example.
You can also use simple string concatenation to fill in your values into your SQL statement, but that's only possible with simple integer or string values, and is generally not recommended because it is subject to SQL injection attack.

Dropdownlist data not insert in query

I select the DropDownList value to insert in query but the value remains blank in query and due to empty value in where condition not any result outcome. I do with different tricks but remain empty
if (chkBoxChanl.Checked)
{
sql += " and channelName = '" + ddlChannel.Text + "' ";
}
if (chkBoxDate.Checked)
{
sql += " and transmissionDate_ between '" + tbFrom.Text + "' and '" + tbTo.Text + "'";
}
if (chkBoxProgrm.Checked)
{
sql += " and programName ='" + ddlProgram.Text + "'";
}
if (chkBoxParty.Checked)
{
sql += " and partiesName like '%" + ddlParty.SelectedValue + "%'";
}
if (chkBoxPerson.Checked)
{
sql += " and personsName like '%" + ddlPerson.SelectedItem + "%'";
}
if (chkBoxProvince.Checked)
{
sql += " and ProvinceName like '%" + ddlProvince.SelectedItem + "%'";
}
if (chkBoxCity.Checked)
{
sql += " and CityName like '%" + ddlCity.Text + "%'";
}
Like
ddlProgram.Text
ddlProvince.SelectedItem
ddlPerson.SelectedValue
selected DropDownList value is shown empty in query.
What can I do to add the selected value in query? Please help me!
I check that when I select the dropdownist values which come on first load then 2md time after press search button dropdownlist values empty and when I press search button it first run Page_Load function and if(!IspostBack) is execute then all dropdownlist selected values become empty which cause to empty values in where clause. Now I want that when I press search button dropdownlist values remain loaded which will resolve the issue to become enpty dropdownlist values. Please guide me further
First of all: you shouldn't concatenate parameters to queries in this way. You expose yourself to SQL injection attacks.
Sorry, new to stackoverflow. Didn't see the comment button
and
programName =' mytext' OR 1 = 1;
DROP Database
Comment anything else.
You cannot concatenate your input field's values directly in your sql query. It makes your system vulnerable to Sql Injection. You should at least encode what you are retrieving from these fields before running such sql query. It is very important that you read this before going ahead.
After reading the above carefully, you can get the value of the selected item on your dropdown. You do this:
yourDropDown.SelectedItem.Value
If it does not return a value, that's probably because you didn't set any value in your dropdown. Remember to set it according to your datasource:
yourDropDown.DataValueField = "TheSourceFieldContainingTheValue";
Build your sql query something like this :
public DataSet ExecuteDataSet(string text, SqlParameter[] paramList)
{
using (SqlCommand sqlCommand = new SqlCommand(text, sqlConnection))
{
if (paramList != null)
{
foreach (var param in paramList)
{
sqlCommand.Parameters.Add(param);
}
}
SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand);
DataSet dataSet=new DataSet();
dataAdapter.Fill(dataSet);
return dataSet;
}
}

SQLite Query returning entire database

First of all, I'm using C#, as well as the C# wrapper for SQLite.
I am attempting to query my SQLite database using the following code, but it continually returns the entire database instead of what is expected. I am extremely new to sql queries, so please look over my query and let me know if you see anything that might be causing the problem.
public DataTable queryDatabase(String column, String filter)
{
string SQL = "SELECT " + column + " FROM SUBCONTRACTOR " + filter;
SQLiteCommand cmd = new SQLiteCommand(SQL);
cmd.Connection = connection;
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
da.Fill(ds);
DataTable dt = ds.Tables[0];
return dt;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return null;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
And here is the code I'm running to call the above method...
dataGridView.DataSource = sqliteQuery.queryDatabase("*", "WHERE GLOPolicy != 'True' OR ALPolicy != 'True' OR WCPolicy != 'True' OR ULPolicy != 'True' AND BusinessName LIKE '%" + bySubBusinessNameMaskedTextBox.Text + "%' AND Contact LIKE '%" + bySubContactNameMaskedTextBox.Text + "%'");
Thanks for any help, as always!
EDIT:
With my query, I am attempting to select all records that have...
(GLOPolicy != true OR ALPolicy != true OR WCPolicy != True OR ULPolicy != True)
AND
BusinessName LIKE [business name variable here]
AND
ContactName LIKE [contact name variable here]
James is right (in comment).
Because AND has higher precedence than OR, your WHERE clause essentially says:
WHERE
GLOPolicy != 'True' OR ALPolicy != 'True' OR WCPolicy != 'True' OR
(ULPolicy != 'True' AND BusinessName LIKE '%x%' AND Contact LIKE '%y%')
You can fix by adding parens around all ORd conditions to ensure that they are evaluated before getting mixed in with the ANDs:
WHERE
(GLOPolicy != 'True' OR ALPolicy != 'True' OR WCPolicy != 'True' OR
ULPolicy != 'True') AND BusinessName LIKE '%x%' AND Contact LIKE '%y%'
Also: I think that your code is vulnerable to SQL-injection attacks. I am not fluent in C#, but there should be some built-in way to pass parameters to your query.
Edit:
It now seems, in the comments, that there is something else going on here.
I would suggest the following debugging methods:
use the recommended way of passing parameters,
try running the query with just one of the LIKE conditions at a time; verify that results are as you expect,
ensure that the parameters you are passing contain what you expect.
Aside from that: Posting your schema and data—since it's only 3 rows—couldn't hurt.

Using items from List<string> in SQL query

Ok, I have a list that consists of a bunch of values from a sql query, that part works fine. What I want to do is use the items in that list to tell another query what to look for. So, what it is saying is that, it should return all columns from CMMReports where PartNumber is like %listItem1..2...3%, Any advice?
List<string> ImportedParts = GetImportedPartNumbers();
string query = "SELECT * FROM CMMReports WHERE (RacfId IS NULL OR RacfId = '') AND (FilePath NOT LIKE '%js91162%') AND PartNumber LIKE %" + ImportedParts + "% ORDER BY CreatedOn DESC;";
Not that I condone this as you should be using parameterized queries. However, this should work:
StringBuilder partNumbers = new StringBuilder();
foreach (string queryValue in ImportedParts)
{
string q = "PartNumber LIKE '%" + queryValue + "%'";
if (string.IsNullOrEmpty(partNumbers.ToString())
{
partNumbers.Append(q);
}
else
{
partNumbers.Append(" OR " + q);
}
}
string query = string.Format("SELECT * FROM CMMReports WHERE (RacfId IS NULL OR RacfId = '') " +
"AND (FilePath NOT LIKE '%js91162%') AND ({0}) " +
"ORDER BY CreatedOn DESC;", partNumbers.ToString());
You might look up the IN clouse for SQL that way you get the answer for the parts that SQL Server can find in the database. Using WHERE x = y for all the items means that if one item can't be found the whole query returns nothing.
I would consider doing this in a stored procedure and passing in your list as an Xml parameter.
See the following article for more info on using Xml parameters in a stored proc:
Passing lists to SQL Server 2005 with XML Parameters - By Jon Galloway
Form there you can easily use your list data inside your stored proc using the Xml syntax and treat it almost as another table of data.
Untested, but you should get the idea:
List<string> ImportedParts = GetImportedPartNumbers();
SqlCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM CMMReports WHERE (RacfId IS NULL OR RacfId = '') AND (FilePath NOT LIKE '%js91162%') AND (";
int i = 0;
foreach (string part in ImportedParts) {
cmd.AddParameterWithValue("#param" + i.ToString(), "%" + part + "%");
if (i != 0) cmd.CommandText += " OR"
cmd.CommandText += " PartNumber LIKE #param" + i.ToString();
i++;
}
cmd.CommandText += ") ORDER BY CreatedOn DESC;";
This solution uses a parameterized query instead of just appending strings in the SQL, which is considered a potential security risk.

Categories

Resources