I want to get data between two dates.I am using a MySql database with my C# winforms. At the time of inserting the dates I converted the date to dd-MM-yyyy and saved these dates in the database having column of type varchar. Now I want to fetch results between two dates here is my code:
string dateFrom = dtp_dfrom.Value.ToString("dd-MM-yyyy");
string dateTo = dtp_dto.Value.ToString("dd-MM-yyyy");
//MessageBox.Show(dateFrom+" "+dateTo);
conn = new MySqlConnection(myconstring);
DataTable dt = new DataTable();
MySqlDataAdapter sda = new MySqlDataAdapter("SELECT trans_date, product_type AS Item, product_quantity, amount, SUM( product_quantity ) AS Qty, SUM( amount ) AS 'Total Price' FROM main_table WHERE trans_date BETWEEN '"+dateFrom+"' AND '"+dateTo+"' GROUP BY product_type", conn);
sda.Fill(dt);
Now the problem is I am not getting the date as required.Anybody can help me out. I am very new to dates formats. Thanks in advance.
I converted the date to dd-MM-yyyy and saved these dates in the
database having column of type varchar
No offense but this is terribly wrong. There is no reason to use varchar as column type for your date values. Use DATE or DATETIME column types instead. That's what they for.
MySQL Data Types
In your case, I suggest you to use DATE column type because it supports YYYY-MM-DD format.
And you should always use parameterized queries. This kind of string manipulations are open for SQL Injection attacks.
string dateFrom = dtp_dfrom.Value.ToString("yyyy-MM-dd");
string dateTo = dtp_dto.Value.ToString("yyyy-MM-dd");
using(MySqlConnection conn = new MySqlConnection(myconstring))
{
DataTable dt = new DataTable();
using(MySqlCommand cmd = new MySqlCommand("SELECT trans_date, product_type AS Item, product_quantity, amount, SUM( product_quantity ) AS Qty, SUM( amount ) AS 'Total Price' FROM main_table WHERE trans_date BETWEEN #dateFrom AND #dateTo GROUP BY product_type"))
{
cmd.Parameters.AddWithValue("#dateFrom", dateFrom);
cmd.Parameters.AddWithValue("#dateTo", dateTo);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd, conn);
sda.Fill(dt);
}
}
You cannot do a between on a varchar column, you have to cast it to datetime/date first.
Like the following:
cast(trans_date as date) BETWEEN '"+dateFrom+"' AND '"+dateTo+"'
Though there is no reason why you are saving a date value into a varchar column, you should modify the table and use the correct columntype so you don't need to cast.
Btw, you should use parameters instead of string manipulations.
You might be looking for STR_TO_DATE
string dateFrom = dtp_dfrom.Value.ToString("yyyy-MM-dd HH:mm:ss");
string dateTo = dtp_dto.Value.ToString("yyyy-MM-dd HH:mm:ss");
MySqlDataAdapter sda = new MySqlDataAdapter("SELECT trans_date, product_type AS Item, product_quantity, amount, SUM( product_quantity ) AS Qty, SUM( amount ) AS 'Total Price' FROM main_table WHERE STR_TO_DATE(trans_date,''%d-%m-%Y'') BETWEEN '"+dateFrom+"' AND '"+dateTo+"' GROUP BY product_type", conn);
You can't use BETWEEN with varchar data, you'll have to use datetime/date as the column type.
It would also be better to use parameters with your query like so:
DataTable dt = new DataTable();
MySqlCommand cmd = new MySqlCommand("SELECT trans_date, product_type AS Item, product_quantity, amount, SUM( product_quantity ) AS Qty, SUM( amount ) AS 'Total Price' FROM main_table WHERE trans_date BETWEEN #from AND #to GROUP BY product_type", conn);
try
{
SqlParameter param;
param = new MySqlParameter("#from", MySqlDbType.DateTime);
param.Value = dateFrom ;
cmd.Parameters.Add(param);
param = new MySqlParameter("#to", MySqlDbType.DateTime);
param.Value = dateTo;
cmd.Parameters.Add(param);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
sda.Fill(dt);
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
Try this, but I stored date using DateTime as data type.
SqlConnection con = new SqlConnection("Data Source=xxx\\SQLEXPRESS;Initial Catalog=abc;Integrated Security=true;");
con.Open();
SqlCommand cmd = new SqlCommand("select p.POID,p.SupplierID,p.SupplierDesc, p.CreateDate, p.PaymentDetails,p.Status,q.Quantity,q.BalQty,q.PartNo from PoToSupplierMaster p inner join PoToSupplierMasterItems q on p.POID=q.SNO where q.PartNo='" + DropDownList3.SelectedItem.Text + "' and p.CreateDate between '" + TextBox1.Text + "' and '" + TextBox2.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView2.DataSource = ds;
GridView2.DataBind();
in my case I used gridview. but its working fine.
Related
I am creating a project that user have to select the date in Combobox but where I have select that date in Combobox that is displaying the error date
String was not recognized as a valid DateTime.'
I am trying to fetch date from database in slq.
Below is my code
System.Data.DataTable dt;
SqlConnection con=new SqlConnection(#"Data Source=krupal;Initial Catalog=LOANNOTICE;Integrated Security=True");
con.Open();
this.cmbmonth.FormatString = "yyyy/ MM/dd";
// DateTime dat = Convert.ToDateTime(cmbmonth.SelectedItem.ToString("yyyy/MM/dd"));
//var date = cmbmonth.Text;
//var d1 = Convert.ToDateTime(cmbmonth.Text);
// MessageBox.Show("" + d1);
string Querie=("SELECT HCODE ,(select top 1 rtrim(Name) From RNSB_TEST.dbo.FC014076 p with(nolock) where convert(varchar,PrdCd) = convert(varchar,HCODE)) as PrdName,count(*) as NoOfAcc,round(Sum(BAL2802),2) as PrintAmt ,round(SUM(IntAmt),2) as TotalInt,0 as TDSAmount, round(SUM(IntAmt),2) as NetIntAmt, round((Sum(BAL2802) + SUM(IntAmt)),2)as TotalAmt from LOANNOTICE.dbo.UNCLAIM_DEPO with(nolock) where EffeDate='"+Convert.ToDateTime(cmbmonth.SelectedText).ToString("yyyy/MM/dd") + "' group by HCODE union SELECT HCODE, (select top 1 rtrim(Name) From RNSB_TEST.dbo.FC014076 p with(nolock) where convert(varchar, PrdCd) = convert(varchar, HCODE)) as PrdName,count(*) as NoOfAcc,round(Sum(MatAmt), 2) as PrintAmt ,round(SUM(IntAmt), 2) as TotalInt,round(sum(TDS_Amount), 2) as TDSAmount, round(SUM(Net_Int), 2) as NetIntAmt, round((Sum(MatAmt) + SUM(Net_Int)), 2) as TotalAmt from LOANNOTICE.dbo.UNCLAIM_DEPO_TDR with(nolock) where EffeDate = '"+Convert.ToDateTime(cmbmonth.SelectedText).ToString("yyyy/MM/dd") + "' group by HCODE");
SqlCommand cmd = new SqlCommand(Querie, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
dt = new System.Data.DataTable();
sda.Fill(dt);
Anyone have a solution please let me know fast.
Thanks.
You need to parse string into valid date time.
Your conversion was wrong, please convert string to date time and then pass to appropriate date fields.
please refer this link .
It draws my attention that you have this blank space here:
this.cmbmonth.FormatString = "yyyy/ MM/dd"
Anyway, you should always check dates passed as string, and throw an exception if you can't cast them:
if (!DateTime.TryParse(_date, out DateTime date))
{
throw new InvalidCastException("Not a valid date.");
}
And last, try to set you SqlCommand parameters this way, is more readable and you don't have to deal with string interpolation (checkout for:
using (DbConnection connection = new SqlConnection("MyConnectionString"))
{
using (DbCommand command = new SqlCommand(connection))
{
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT * FROM MyTable WHERE Date = #Date";
command.Parameters.Add("#Date", SqlDbType.Date);
command.Parameters["#Date"].Value = date;
}
}
Give it a try! :)
Regards!
Filter data between two dates I got the following error:
System.Data.SqlClient.SqlException: the Conversion of a varchar data
type to a datetime data type resulted in an out-of-range.
My code is:
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT daytime AS DATE, COLUMN_2 AS SHIFT, COLUMN_3 AS 'PART NO',COLUMN_4 AS 'PART NAME',BSNO AS 'BASKET NUMBER',Spare1 AS MATERIAL, CAS6 AS 'CASCADE RINSE 6 TIME (sec)',DRY AS 'DRYER TIME (sec)',TEMP1 AS 'DRYER TEMP (°c)' FROM Table_2 WHERE daytime BETWEEN '" + dateTimePicker1.Value.ToString() + "' AND '" + dateTimePicker2.Value.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
metroGrid1.DataSource = dt;
con.Close();
I can't solve this error.
Whenever you find yourself converting a .Net DateTime value to a string for use in SQL, you're doing something VERY wrong.
The pattern demonstrated below contains several improvements over the code in the question. Most notably, the code in the question is vulnerable to sql injection attacks, while this code is not. But there are other improvements here, too.
//most datetime comparisons want an *exclusive* upper bound, but the BETWEEN operator bounds are inclusive on both ends
var sql = "SELECT daytime AS DATE, COLUMN_2 AS SHIFT, COLUMN_3 AS 'PART NO',COLUMN_4 AS 'PART NAME',BSNO AS 'BASKET NUMBER',Spare1 AS MATERIAL, CAS6 AS 'CASCADE RINSE 6 TIME (sec)',DRY AS 'DRYER TIME (sec)',TEMP1 AS 'DRYER TEMP (°c)' FROM Table_2 WHERE daytime >= #daytimeStart AND daytime < #daytimeEnd ;";
var dt = new DataTable();
//Don't try to re-use your connection object.
// ADO.Net connection pooling means you should create a new connection for most queries
using (var con = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, con))
using (var da = new SqlDataAdapter(cmd))
{ //These using blocks guarantee the connection is closed, **even if an exception is thrown**. The original code would have left the connection open if you had an exception.
//This is the correct way to include user data with your sql statement
// **NEVER** use string concatenation to substitute values into SQL strings
cmd.Parameters.Add("#daytimeStart", SqlDbType.DateTime).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#daytimeEnd", SqlDbType.DateTime).Value = dateTimePicker2.Value;
//the Fill() method opens and closes the connection as needed
da.Fill(dt);
}
metroGrid1.DataSource = dt;
Here it is again without the extra comments, so you can see how the new pattern isn't significantly longer than the original code in the question:
var sql = "SELECT daytime AS DATE, COLUMN_2 AS SHIFT, COLUMN_3 AS 'PART NO',COLUMN_4 AS 'PART NAME',BSNO AS 'BASKET NUMBER',Spare1 AS MATERIAL, CAS6 AS 'CASCADE RINSE 6 TIME (sec)',DRY AS 'DRYER TIME (sec)',TEMP1 AS 'DRYER TEMP (°c)' FROM Table_2 WHERE daytime >= #daytimeStart AND daytime < #daytimeEnd ;";
var dt = new DataTable();
using (var con = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, con))
using (var da = new SqlDataAdapter(cmd))
{
cmd.Parameters.Add("#daytimeStart", SqlDbType.DateTime).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#daytimeEnd", SqlDbType.DateTime).Value = dateTimePicker2.Value;
da.Fill(dt);
}
metroGrid1.DataSource = dt;
So i have a sql statement in my C# Code to try and pull data between two date ranges. Only thing is, nothing shows up.
OpenConnection(conn);
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("Select CampaignName AS 'CAMPAIGN NAME', campaignDescription AS 'CAMPAIGN DESCRIPTION', CASE WHEN EndDate >= GETDATE() and StartDate <= GETDATE() THEN 'ACTIVE' WHEN StartDate >= GETDATE() THEN 'PENDING' ELSE 'CLOSED' END as 'CURRENT STATUS', CONVERT(VARCHAR(11), StartDate,106) + ' - ' + CONVERT(VARCHAR(11),EndDate,106) AS 'CAMPAIGN DATES', Discount AS 'DISCOUNT', [Target] AS 'TARGET', Uptake AS 'UPTAKE', AddedBy AS 'ADDED BY', DateAdded AS 'DATE ADDED' FROM Tbl_Campaign WHERE startDate BETWEEN #from AND #to", conn);
try
{
SqlParameter param;
param = new SqlParameter("#from", SqlDbType.DateTime);
param.Value = txtStartDate.Text;
cmd.Parameters.Add(param);
param = new SqlParameter("#to", SqlDbType.DateTime);
param.Value = txtDateEnd.Text;
cmd.Parameters.Add(param);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
If you scroll to the end of my Sql Command, you will see two variables for my to and from date. I tried executing this piece of code in SQL, and it works if i manually parse the dates, with '' quotation marks. I think thats what is why its not retrieving data. Could someone help me with this request?
I used a text box to get the date since your code includes "txtStartDate.Text". So, I tried your code with a simple query only to get the data in a date range. It works well. So, I think there's an issue in another place in your query.
This is the code I tried:
con = new SqlConnection();
string _connectionString = GetConnectionString();
con.ConnectionString = _connectionString;
con.Open();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("SELECT * FROM FORDSUMD WHERE Dated BETWEEN #from AND #to",con);
try
{
SqlParameter param;
param = new SqlParameter("#from", SqlDbType.DateTime);
param.Value = txtStartDate.Text;
cmd.Parameters.Add(param);
param = new SqlParameter("#to", SqlDbType.DateTime);
param.Value = txtDateEnd.Text;
cmd.Parameters.Add(param);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
public string GetConnectionString(string databaseName = "", string serverName = "")
{
SqlConnectionStringBuilder conString = new SqlConnectionStringBuilder();
if (string.IsNullOrEmpty(serverName))
serverName = ConfigurationManager.AppSettings["ServerName"];
//Assing SQl server name
conString.DataSource = serverName;
conString.InitialCatalog = string.IsNullOrEmpty(databaseName) ? ConfigurationManager.AppSettings["DBName"] : databaseName;
conString.IntegratedSecurity = false;
conString.UserID = ConfigurationManager.AppSettings["UserId"];
conString.Password = ConfigurationManager.AppSettings["Password"];
return conString.ConnectionString;
}
If you want to use DateTimePicker control instead of the textbox control, simply replace txtStartDate.Text by dtpStart.Value(DateTimePicker) and txtDateEnd.Text by dtpEnd.Value. It will work.
I'm trying to select a field from my table where date is less than today.
connect.Open();
command.Connection = connect;
today = DateTime.Today.ToString("dd/MM/yyyy");
string query = "select attendance as [Attend], Emp_UserId as ID, 'Date_ofday' as [Today Date] , Emp_UserName as Name ,Delay_Hours as [Delay Hours] from Attendance where Date_ofday > '"+ DateTime.Parse(today) + "' ";
command.CommandText = query;
OleDbDataAdapter da1 = new OleDbDataAdapter(command);
DataTable dt1 = new System.Data.DataTable();
da1.Fill(dt1);
dataGridView1.DataSource = dt1;
This gives a data type miss or missing operator error, using an Access DB.
You are converting a DateTime to string and then parse it back to DateTime in the next line, this doesn't make sense. I think you should use parameters, see if this works, I don't use MySql:
connect.Open();
command.Connection = connect;
todday = DateTime.Today.ToString("dd/MM/yyyy");
string query = "select attendance as [Attend], Emp_UserId as ID, 'Date_ofday' as [Today Date] , Emp_UserName as Name ,Delay_Hours as [Delay Hours] from Attendance where Date_ofday > #Today";
command.CommandText = query;
OleDbDataAdapter da1 = new OleDbDataAdapter(command);
DataTable dt1 = new System.Data.DataTable();
da1.SelectCommand.Parameters.AddWithValue("#Today", DateTime.Today);
da1.Fill(dt1);
dataGridView1.DataSource = dt1;
In the case you are using MS Access the query becomes:
string query = "select attendance as [Attend], Emp_UserId as ID, 'Date_ofday' as [Today Date] , Emp_UserName as Name ,Delay_Hours as [Delay Hours] from Attendance where Date_ofday > ?";
I have an error when I try to run my program:
The conversion of a varchar data type to a datetime data type
resulted in an out-of-range value.
Is there anything wrong with my select statement?
int month=0;
if (RadioButtonList1.SelectedIndex == 0)
{ month = 1; }
else if(RadioButtonList1.SelectedIndex == 1)
{ month = 2; }
else if(RadioButtonList1.SelectedIndex == 2)
{ month = 3; }
SqlCommand cmd = new SqlCommand("SELECT thDate, thType, thAmountIn, thAmountOut from [Transaction] Where thDate > dateadd(month, -" + month + ", GETDATE())", myConnection);
da = new SqlDataAdapter(cmd);
myConnection.Open();
da.Fill(ds, "[Transaction]");
myConnection.Close();
if (!IsPostBack)
{
ViewState["vs_Transaction"] = (DataTable)ds.Tables["Transaction"];
GridView1.DataSource = ds.Tables["Transaction"];
GridView1.DataBind();
The below is my database table for thDate
The problem is that you're storing the data as Varchar, and filling the datatable, that probably will expect a Datetime. You should cast the values in the query in two places:
In the select, for returning as a Date
In the Where, because you're comparing a Date against a
Varchar.
So, your select clause will be
SqlCommand cmd = new SqlCommand("SELECT Convert(datetime, thDate,103) as thDate, thType, thAmountIn, thAmountOut from [Transaction] Where Convert(datetime, thDate,103)> dateadd(month, -" + month + ", GETDATE())", myConnection);