Filter data from DB with datetimepicker - c#

I have two columns with date_of_delivery and date_of_receipt. I want to filter my data
private void button25_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
if(radioButton9.Checked)
{
if ((Convert.ToDateTime(dateTimePicker3.Value)) <= (Convert.ToDateTime(dateTimePicker4.Value)))
{
try
{
string query = "SELECT work_id, surname, first_name, patronymic, type_of_service.name_type_of_service, date_of_receipt, date_of_delivery, car_model.name_model, price_for_work FROM mechanic INNER JOIN work ON work.mechanic_id = mechanic.mechanic_id INNER JOIN type_of_service ON work.type_of_service_id = type_of_service.type_of_service_id INNER JOIN car ON work.car_id = car.car_id INNER JOIN car_model ON car.car_model_id = car_model.car_model_id WHERE work.date_of_receipt >= '" + Convert.ToDateTime(dateTimePicker3.Value) + "' AND work.date_of_delivery <= '" + Convert.ToDateTime(dateTimePicker4.Value) + "'";
MessageBox.Show("" + query);
dataGridView2.DataSource = query;
SqlDataAdapter da = new SqlDataAdapter(query, SqlConn);
da.Fill(ds, query);
dataGridView2.DataSource = ds.Tables[query];
}
catch (Exception e2)
{
MessageBox.Show(e2.Message);
}
}
else
{
MessageBox.Show("Дата начала ремонта не может быть позже его завершения ");
}
}
else if(radioButton10.Checked)
{
string query = "SELECT work_id, surname, first_name, patronymic, type_of_service.name_type_of_service, date_of_receipt, date_of_delivery, car_model.name_model, price_for_work FROM mechanic INNER JOIN work ON work.mechanic_id = mechanic.mechanic_id INNER JOIN type_of_service ON work.type_of_service_id = type_of_service.type_of_service_id INNER JOIN car ON work.car_id = car.car_id INNER JOIN car_model ON car.car_model_id = car_model.car_model_id WHERE work.price_for_work BETWEEN " + Convert.ToInt32(textBox16.Text) + " AND " + Convert.ToInt32(textBox17.Text) + "";
MessageBox.Show("" + query);
dataGridView2.DataSource = query;
SqlDataAdapter da = new SqlDataAdapter(query, SqlConn);
da.Fill(ds, query);
dataGridView2.DataSource = ds.Tables[query];
}
}
However, the data is not sorted. Because the database format of the date 01.02.2015 . How to make sure everything works

As I wrote in the comments, date types does not have a format.
You are sending a string that represents a date value to the database, (the default .ToString() of the DateTime object is called since there is an implicit conversion from date to string when you are concatenating the DateTime to the sql string).
When using strings for a date value in sql it's best to use ANSI-SQL format which is yyyy-MM-dd. This format guarantees that SQL Server will interpret the string as a proper date.
However, concatenating strings to create an SQL statement is a security hazard, since it's an opening for SQL injection attacks.
The proper way is to use parameterized queries or stored procedures.
Replace your query's where clause from this
WHERE work.date_of_receipt >= '" + Convert.ToDateTime(dateTimePicker3.Value) +
"' AND work.date_of_delivery <= '" + Convert.ToDateTime(dateTimePicker4.Value) + "'"
to this:
WHERE work.date_of_receipt >= #date_of_receipt
AND work.date_of_delivery <= #date_of_delivery
Then use the SqlDataAdapter's SelectCommand's Parameters collection to add the values for the parameters:
SqlDataAdapter da = new SqlDataAdapter(query, SqlConn);
da.SelectCommand.Parameters.Add("#date_of_receipt ", SqlDbType.Date).Value = dateTimePicker3.Value;
da.SelectCommand.Parameters.Add("#date_of_delivery", SqlDbType.Date).Value = dateTimePicker4.Value;
(Note that the add command returns a reference to the SqlParameter you've just added, therefor you can write the .Value to specify the value of the parameter when adding it to the SelectCommand.
Note that the value of the DateTimePicker is already a DateTime type, so there is no need to use Convert.ToDateTime when adding it.
Do the same thing with all other queries (of course, don't forget to use the proper data types for the parameters).

System.DateTime dt16 = System.DateTime.Parse(textBox16.Text);
string sTextBox16 = dt16.ToString("dd.MM.yyyy");
System.DateTime dt17 = System.DateTime.Parse(textBox17.Text);
string sTextBox17 = dt17.ToString("dd.MM.yyyy");
string query = "SELECT Required Columns WHERE work.date_of_receipt >= "+sTextBox16 +"' AND work.date_of_delivery <= '" + sTextBox17 +"'";

Related

Searching between two datetimepicker in access database

Code:
private void button2_Click(object sender, System.EventArgs e)
{
OleDbDataAdapter dbc = new OleDbDataAdapter("SELECT ReceiptID,ID,Name,Paid,Due FROM lastpays where [Dateofpayment] >= "+ dateTimePicker1.Value.Date + " AND [Dateofpayment] < " + dateTimePicker2.Value.Date + "", con);
DataTable data = new DataTable();
dbc.Fill(data);
dataGridView1.DataSource = data;
}
Error:
System.Data.OleDb.OleDbException: 'Syntax error (missing operator) in
query expression '[Dateofpayment] >= 11-01-2020 12:00:00 AM AND
[Dateofpayment] < 11-01-2020 12:00:00 AM'.'
MS Access (JET Red) requires date literals in SQL to be in the form #MM/dd/yyyy#.
Your code however inserts the default string representation of a DateTime value using CurrentCulture, without using any delimiters.
Because you're directly concatenating String values with DateTime values, which invokes DateTime.ToString() which is CurrentCulture-sensitive.
Use parameters to avoid this issue entirely, and to prevent SQL injection.
Also, you're using the same dateTimePicker instance for both values - I think you mean to use dateTimePicker1 and dateTimePicker2 - though you should rename them to minDatePicker and maxDatePicker to be clear what their purpose is.
const String sql = #"SELECT ReceiptID,ID,Name,Paid,Due FROM lastpays where [Dateofpayment] >= ? AND [Dateofpayment] < ?";
OleDbCommand cmd = connection.CreateCommand();
cmd.CommandText = sql;
OleDbParameter pFrom = cmd.CreateParameter();
pFrom.OleDbType = OleDbType.Date;
pFrom.Value = dateTimePicker1.Value.Date;
cmd.Parameters.Add( pFrom );
OleDbParameter pTo = cmd.CreateParameter();
pTo.OleDbType = OleDbType.Date;
pTo.Value = dateTimePicker2.Value.Date;
cmd.Parameters.Add( pTo );
OleDbDataAdapter da = new OleDbDataAdapter( selectCommand: cmd );
DataTable data = new DataTable();
da.Fill( data );
dataGridView1.DataSource = data;
Even though parameters are preferred, the questioneer deserves an answer why the code is failing.
The date values must be converted to valid string expressions:
OleDbDataAdapter dbc = new OleDbDataAdapter("SELECT ReceiptID,ID,Name,Paid,Due FROM lastpays where [Dateofpayment] >= #"+ dateTimePicker1.Value.Date.ToString("yyyy'/'MM'/'dd") + "# AND [Dateofpayment] < #" + dateTimePicker2.Value.Date.ToString("yyyy'/'MM'/'dd") + "#", con);

Condition statements for a single row data value in a database

I am using C# to create a windows form.
I am trying to set a condition statement for a particular value that is retrieved from my database by the onclick of a button. The datatype of the column is 'integer'.
Below is my code:
string checkquantity = "SELECT `inventory_item`.`Item_Quantity_Available`FROM `inventory_item` , `patient`, `out_treatment`WHERE `inventory_item`.`Item_ID` = `out_treatment`.`Inventory_ID`AND `patient`.`Patient_ID` = `out_treatment`.`Patient_ID`AND `out_treatment`.`Patient_ID`= '" + pid + "' ";
MySqlCommand selectout = new MySqlCommand(checkquantity, connect);
MySqlDataAdapter selectdata = new MySqlDataAdapter(checkquantity, connect);
DataTable selecttable = new DataTable();
selectdata.Fill(selecttable);
DataSet ds = new DataSet();
selectdata.Fill(selecttable);
selectdata.Fill(ds);
int i = ds.Tables[0].Rows.Count;
if ( i <= 0)
{
MessageBox.Show("Out of Stock");
}
I'm new with c#.
I don't think the int i = ds.Tables[0].Rows.Count; is the right way.
Any help is much appreciated.
First of all, like #Flydog57 said, you should not concatenate your sql query. The best way is to use parameters, for example:
string checkquantity = "SELECT i.Item_Quantity_Available " +
" FROM inventory_item i JOIN out_treatment t ON i.Item_Id = t.Inventory_ID " +
" JOIN patient p ON t.Patient_ID = p.PatiendID " +
" WHERE t.Patient_ID = #Patiend_ID";
MySqlCommand selectout = new MySqlCommand(checkquantity, connect);
// set the parameter value
selectout.Parameters.AddWithValue("#Patiend_ID", patient_id_value);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
if ((int)rdr["Item_Quantity_Available"] == 0)
MessageBox.Show("Out of Stock");
}
In second place, you could use a MySqlDataReader to verify that Item_Quantity_Available is equal to 0, like in the previous example. Otherwise, If you just wants to verify if there is data, the condition could be something like that:
if (!rdr.Read())
{
MessageBox.Show("Out of Stock");
}
The third improvemente is to join tables with the join clause.

Create list from sqlite database join function

I'm trying to make a list from a sqlite database join. I'd like to get the date values when the specific machine is selected. Example: Machine A is selected, it makes a list of 05/25/15, 05/30/15, 05/20/15. With the join I'm using it wants to spit out the column name but not the values. It's an ambiguous column error with sqlite.
void fill_listbox_Dates()
{
string Machine_Name_listbox = listboxMachines.SelectedItem.ToString();
string databaseString = "datasource=LinacDatabase.db";
string DateQuery = "SELECT Date FROM Machines as E1 INNER JOIN Date as E2 ON Machines.Machine= " + Machine_Name_listbox + "";
SQLiteConnection conDatabase = new SQLiteConnection(databaseString);
SQLiteCommand cmdDataBase = new SQLiteCommand(DateQuery, conDatabase);
SQLiteDataReader ReadDate;
try
{
conDatabase.Open();
ReadDate = cmdDataBase.ExecuteReader();
while (ReadDate.Read())
{
List<string> Dates = ReadDate.GetString(1);
listboxDates.Items.Add(Dates);
}
}
So the problem was that I had to insert a single quote value around to double quote of the Machine_Name_List box string. Otherwise the sqlite datareader will think the value is a column name. So it should read,
string DateQuery = "SELECT Date FROM Machines as E1 INNER JOIN Date as E2 ON Machines.Machine= '" + Machine_Name_listbox + "'";

SQL LIKE % NOT SEARCHING

I want to perform a simple search using the SQL LIKE function. Unfortunately for some reason , it doesn't seem to be working. Below is my code.
private void gvbind()
{
connection.Open();
string sql = "";
if (txtSearch.Text.Trim() == "")
{
sql = "SELECT a.cname,[bid],b.[bname],b.[baddress],b.[bcity],b.[bstate],b.[bpostcode],b.[bphone],b.[bfax],b.[bemail] FROM [CLIENT] a INNER JOIN [BRANCH] b ON a.clientID=b.clientID ORDER BY a.[clientID]";
}
else
{
sql = "SELECT a.cname,[bid],b.[bname],b.[baddress],b.[bcity],b.[bstate],b.[bpostcode],b.[bphone],b.[bfax],b.[bemail] FROM [CLIENT] a INNER JOIN [BRANCH] b ON a.clientID=b.clientID WHERE b.[bname] LIKE '%#search%' ORDER BY a.[clientID]";
}
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.Parameters.AddWithValue("#search", txtSearch.Text.Trim());
cmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
DataSet ds = new DataSet();
adp.Fill(ds);
connection.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvBranch.Enabled = true;
gvBranch.DataSource = ds;
gvBranch.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvBranch.DataSource = ds;
gvBranch.DataBind();
int columncount = gvBranch.Rows[0].Cells.Count;
gvBranch.Rows[0].Cells.Clear();
gvBranch.Rows[0].Cells.Add(new TableCell());
gvBranch.Rows[0].Cells[0].ColumnSpan = columncount;
gvBranch.Rows[0].Cells[0].Text = "No Records Found";
}
ds.Dispose();
}
the above method is called in the Page_Load() method using
if((!Page.IsPostBack))
{
gvBind();
}
it is called on button search click aslo. However, it return No record found when ever i perform the search.
Use
LIKE '%' + #search + '%'
instead of
LIKE '%#search%'
Full query;
...
else
{
sql = "SELECT a.cname,[bid],b.[bname],b.[baddress],b.[bcity],b.[bstate],b.[bpostcode],b.[bphone],b.[bfax],b.[bemail] FROM [CLIENT] a INNER JOIN [BRANCH] b ON a.clientID=b.clientID WHERE b.[bname] LIKE '%' + #search + '%' ORDER BY a.[clientID]";
}
And actually, you don't need to use square brackets ([]) every column in your query. Use them if your identifiers or object names are a reserved keyword.
Thanks. It works , but any explanation for that?
The main problem is here, your query parameter is inside quotes. In quotes, SQL Server will recognize it as a string literal and never sees it as a parameter.

Problem with WHERE columnName = Data in MySQL query in C#

I have a C# webservice on a Windows Server that I am interfacing with on a linux server with PHP. The PHP grabs information from the database and then the page offers a "more information" button which then calls the webservice and passes in the name field of the record as a parameter. So i am using a WHERE statement in my query so I only pull the extra fields for that record. I am getting the error:
System.Data.SqlClient.SqlException:Invalid column name '42'
Where 42 is the value from the name field from the database.
my query is
string selectStr = "SELECT name, castNotes, triviaNotes FROM tableName WHERE name =\"" + show + "\"";
I do not know if it is a problem with my query or something is wrong with the database, but here is the rest of my code for reference.
NOTE: this all works perfectly when I grab all of the records, but I only want to grab the record that I ask my webservice for.
public class ktvService : System.Web.Services.WebService {
[WebMethod]
public string moreInfo(string show) {
string connectionStr = "MyConnectionString";
string selectStr = "SELECT name, castNotes, triviaNotes FROM tableName WHERE name =\"" + show + "\"";
SqlConnection conn = new SqlConnection(connectionStr);
SqlDataAdapter da = new SqlDataAdapter(selectStr, conn);
DataSet ds = new DataSet();
da.Fill(ds, "tableName");
DataTable dt = ds.Tables["tableName"];
DataRow theShow = dt.Rows[0];
string response = "Name: " + theShow["name"].ToString() + "Cast: " + theShow["castNotes"].ToString() + " Trivia: " + theShow["triviaNotes"].ToString();
return response;
}
}
Quick solution:
I believe you need single quotes in your selectStr:
string selectStr =
"SELECT name, castNotes, triviaNotes FROM tableName WHERE name = '" + show + "'";
More information:
In .NET, you'll want to be sure you close out any connections explicitly when you no longer need them. The easiest way to do this is to wrap using statements around any types that implement IDisposable, such as SqlConnection in this case:
using(SqlConnection conn = new SqlConnection(connectionStr))
{
SqlDataAdapter da = new SqlDataAdapter(selectStr, conn);
DataSet ds = new DataSet();
da.Fill(ds, "tableName");
DataTable dt = ds.Tables["tableName"];
DataRow theShow = dt.Rows[0];
string response = "Name: " + theShow["name"].ToString() + "Cast: " + theShow["castNotes"].ToString() + " Trivia: " + theShow["triviaNotes"].ToString();
return response;
}
Additionally, it looks like your code could be easily subject to SQL injection. What if someone submits a form with the value: fake name' OR 1=1;DROP DATABASE someDbName;--?
You'll want to take advantage of SQL parameters, something like:
SqlCommand cmd = new SqlCommand(
"SELECT name, castNotes, triviaNotes FROM tableName WHERE name = #show", conn);
cmd.Parameters.AddWithValue("#show", show);
Shouldn't the WHERE clause be WHERE name = '" + show + "'"; Strings should be enclosed in single quotes and not double quotes for SQL statements.
Also the System.Data.SqlClient namespace is for SQL Server and not MySQL. See MySQL official docs for connecting to MySQL via C#.

Categories

Resources