I'm inserting a datetime field to sql server. From my local computer it works just fine. example: the datetime field in sql server is : "2013-07-31 08:00:00.000", but when I run the application form the server it switches the day and month and insert it like this:
"2013-07-31 15:15:00.000".
My relevant page loads some entries from the sql server depending on today's date.
Like this:
public List<act_event> return_event_list(DateTime date) //return all events for spesific date
{
List<act_event> event_list = new List<act_event>();
String date_sql = date.ToString("yyyy-MM-dd");
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con, "select * from act_events where '" + date_sql + "'>=(CAST(e_start as DATE)) and '" + date_sql + "'<=(CAST(e_end as DATE))"))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
act_event a_event = new act_event();
a_event.e_num = Convert.ToInt32(rdr["e_num"]);
a_event.name = rdr["e_name"].ToString();
a_event.start = Convert.ToDateTime(rdr["e_start"]);
a_event.end = Convert.ToDateTime(rdr["e_end"]);
a_event.description = rdr["e_description"].ToString();
a_event.address = rdr["e_address"].ToString();
event_list.Add(a_event);
}
}
}
}
return event_list;
}
This is how I insert the datetime fields:
public void add_event(act_event add_avent)
{
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con, "insert into act_events values(#e_name, #e_start, #e_end, #e_description, #e_address)"))
{
cmd.Parameters.AddWithValue("#e_name", add_avent.name);
SqlParameter param2 = new SqlParameter("#e_start", SqlDbType.DateTime);
param2.Value = add_avent.start;
cmd.Parameters.Add(param2);
SqlParameter param3 = new SqlParameter("#e_end", SqlDbType.DateTime);
param3.Value = add_avent.end;
cmd.Parameters.Add(param3);
//cmd.Parameters.Add(new SqlParameter("#e_start", SqlDbType.DateTime));
//cmd.Parameters["#e_start"].Value = DateTime.Parse(add_avent.start.ToString());
//cmd.Parameters.Add(new SqlParameter("#e_end", SqlDbType.DateTime));
//cmd.Parameters["#e_end"].Value = DateTime.Parse(add_avent.end.ToString());
cmd.Parameters.AddWithValue("#e_description", add_avent.description);
cmd.Parameters.AddWithValue("#e_address", add_avent.address);
cmd.ExecuteNonQuery();
}
//using (SqlCommand cmd2=create_command
}
}
I tried changing the select command, adding this:
using (SqlCommand cmd = create_command(con, "select * from act_events where ( '" + date_sql + "'>=(CAST(e_start as DATE)) and '" + date_sql + "'<=(CAST(e_end as DATE)) ) or ( '" + date_sql2 + "'>=(CAST(e_start as DATE)) and '" + date_sql2 + "'<=(CAST(e_end as DATE)) ) "))
but for some of the dates it gives me an error:
Conversion failed when converting date and/or time from character
string.
What should I do?
EDIT:
I tried to run the query from the sql studio itself like this:
select * from act_events where ( '2013-08-03'>=(CAST(e_start as DATE)) and '2013-08-03'<=(CAST(e_end as DATE)) ) or ( '2013-03-08'>=(CAST(e_start as DATE)) and '2013-03-08'<=(CAST(e_end as DATE)) )
it gives me:
But if I run it like this: (different date)
select * from act_events where ( '2013-07-30'>=(CAST(e_start as DATE)) and '2013-07-30'<=(CAST(e_end as DATE)) ) or ( '2013-30-07'>=(CAST(e_start as DATE)) and '2013-30-07'<=(CAST(e_end as DATE)) )
it gives me this error:
EDIT2:
After James suggestion I made a parameterized query like this:
String date_sql = date.ToString("yyyy-MM-dd");
String date_sql2 = date.ToString("yyyy-dd-MM");
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con, "select * from act_events where #date1>=(CAST(e_start as DATE)) and #date2<=(CAST(e_end as DATE))"))
{
cmd.Parameters.AddWithValue("#date1", date_sql);
cmd.Parameters.AddWithValue("#date2", date_sql);
cmd.Parameters.AddWithValue("#date3", date_sql2);
cmd.Parameters.AddWithValue("#date4", date_sql2);
which still won't load the correct entries from the sql server
Then I tried this query:
String date_sql = date.ToString("yyyy-MM-dd");
String date_sql2 = date.ToString("yyyy-dd-MM");
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con, "select * from act_events where ( #date1>=(CAST(e_start as DATE)) and #date2<=(CAST(e_end as DATE)) ) or ( #date3>=(CAST(e_start as DATE)) and #date4<=(CAST(e_end as DATE)) )"))
{
cmd.Parameters.AddWithValue("#date1", date_sql);
cmd.Parameters.AddWithValue("#date2", date_sql);
cmd.Parameters.AddWithValue("#date3", date_sql2);
cmd.Parameters.AddWithValue("#date4", date_sql2);
And again it just give me:
Conversion failed when converting date and/or time from character string.
It's never ever really a good idea to try pass date/time's to SQL as string from the client unless you are absolutely certain of the server locale.
Switching to a parameterized query should resolve your issue.
The problems you encounter are due to string to date conversions in one point or another, both on the client and the server's side
You don't need to do any conversionf to string or date if you use a parameterized query and you pass DateTime values, provided of course that the type of your table's fields is also a date type.
The following code makes no conversions at all:
DateTime date1=DateTime.Today.AddMonths(-1);
DateTime date2=DateTime.Today.AddMonths(1);
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con,
"select * from act_events where " +
" (#date1>=e_start and #date1 <= e_end) " +
" or (#date2>= e_start and #date2 <= e_end) "))
{
cmd.Parameters.AddWithValue("#date1", date1);
cmd.Parameters.AddWithValue("#date2", date2);
You don't need to specify the same date multiple times. If this query doesn't work it's either because the e_start and e_end fields are text fields or the WHERE clause is not what you expected.
You should also check whether #date2 is used correctly. Your query seems to look for records that cover #date1 or don't cover #date2. Is this correct?
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!
I want to display a count on a label for all the rows that fall between 6AM and 8AM. I have a datetimepicker that I want to also use to select the day for all the rows that should be counted. I have tried several different ways to format my SELECT statement but nothing has worked. I either get datetime conversion error or wrong syntax.
var sql = "SELECT RTFPressTableID" +
"FROM RTFPressTables" +
"WHERE PressCloseTime BETWEEN CONVERT(DATE, 'Date 06:00:00:000 AM',109) >= #Date AND CONVERT(DATE, 'Date 08:00:00:000 AM',109) <= #Date";
using (SqlConnection conn = new SqlConnection("Data Source = ; Initial Catalog = ; Integrated Security = True"))
{
conn.Open();
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add("#Date", SqlDbType.DateTime);
command.Parameters["#Date"].Value = dateTimePicker1.Value.Date;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
}
}
}
What date time should "'Date 06:00:00:000 AM'" represent?
And why do you use "BETWEEN" and then ">=" resp. "<=" in it's arguments? That's not the right syntax. Either use BETWEEN or >= and <=. Though I guess < is actually what you want for the second operator.
You probably want:
var sql = #"
SELECT RTFPressTableID
FROM RTFPressTables
WHERE PressCloseTime >= dateadd(hour, 6, #Date)
AND PressCloseTime < dateadd(hour, 8, #Date);";
...
I think you want the following:
var sql = #"SELECT RTFPressTableID
FROM RTFPressTables
WHERE PressCloseTime BETWEEN DATEADD(day, DATEDIFF(day, 0, #Date), '06:00:00') AND DATEADD(day, DATEDIFF(day, 0, #Date), '08:00:00')";
using (SqlConnection conn = new SqlConnection("Data Source = ; Initial Catalog = ; Integrated Security = True"))
{
conn.Open();
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add("#Date", SqlDbType.Date);
command.Parameters["#Date"].Value = dateTimePicker1.Value.Date;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
}
}
}
Which has 3 changes from your code:
Spaces are added to the SQL string as mentioned in the comments. In fact using a multi-line string (verbatim string literal) which is much easier to use for SQL strings.
The datatype of the #Date parameter is now of type date instead of datetime.
Most importantly the between statement is corrected to add the times to the date provided and use them as the limits.
Ref: Add Time to DateTime
You need to give spaces in your quotation marks after plus to avoid string concatenation. Something like this:
"SELECT RTFPressTableID" +
" FROM RTFPressTables" +
" WHERE PressCloseTime
how to insert the current time using ado.net sql command. getting error saying The "conversion of a varchar data type to a datetime data type resulted in an out-of-range value."
code
DateTime NowTime = DateTime.Now;
string usecase = "manhole";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
con.Open();
SqlCommand cmdInsert = new SqlCommand("insert into sms values('" + usecase + "','" + smsbody + "','" + NowTime + "')", con);
try
{
cmdInsert.ExecuteNonQuery();
}
columns
updtd_date is datetime
query
INSERT INTO sms (usecase, sms, updtd_date)
VALUES ('manhole','level is low at : 22/01/2018 15:56:20','22/01/2018 16:18:28');
You should use a parametized query instead of concatenating strings, what you are doing is asking for an SQL Injection. Also, you should dispose commands and connections after use them in order to release memory.
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
{
using (var command = new SqlCommand("insert into sms (col1) values(#col1"))
{
command.Parameters.AddWithValue("#col1", DateTime.Now);
con.Open();
command.ExecuteNonQuery();
}
}
Use The Function GETDATE() To Get the System Date and Time.
Change NowTime
"insert into sms values('" + usecase + "','" + smsbody + "','" + NowTime + "')"
To This
"insert into sms values('" + usecase + "','" + smsbody + "',GETDATE())"
Executing the SQL Statements Like this Can Cause SQL Injection, So I Recommend using Parameter may Be Something Like this
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("insert into sms values(#usecase,#smsbody,GETDATE())", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#usecase", SqlDbType.VarChar).Value = usecase;
cmd.Parameters.Add("#smsbody", SqlDbType.VarChar).Value = smsbody;
con.Open();
cmd.ExecuteNonQuery();
}
}
I think you need to be specific with the date format in SQL if you inserting a date if you not using paramater:
string nowDate = DateTime.Now.ToString("dd MMM yyy HH:mm:ss");
string sql = "insert into #dateT values('"+nowDate+"')";
This results to this in my pc
insert into #dateT values('22 Jan 2018 13:27:04');
I have to datetimepickers FromDate and ToDate, and want to do select data between to dates,
I have written the query
select * from tbl where pDate>='" + dtpFrom.value + "'and pDate<='" + dtpTo.value + "'");
This query giving error
Data type mismatch in criteria expression
But datatype is Date/Time in ms access table.
Looks like you try to put single quotes for your DateTime values. # for dates and ' for strings but they required for literal SQL queries.
If you use parameterize queries, you will not need them.
using(var con = new OleDbConnection(conString))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = "select * from tbl where pDate >= ? and pDate <= ?"
cmd.Parameters.AddWithValue("?", dtpFrom.Value);
cmd.Parameters.AddWithValue("?", dtpTo.Value);
...
...
}
I am trying to insert into a SQL Server database using a C# application.
In C# I am using datetime.now to get the current datetime:
order.PendingDateTime = DateTime.Now;
This gives me 25/07/2014 11:30:17.
In the SQL Server table the datatype is datetime. Which holds the data as 2014-07-23 14:54:01.607 for example.
However running the value 25/07/2014 11:30:17 using a normal insert script it inserts into the SQL Server table fine but displays in the table as 2014-07-25 11:30:17. (This is ok)
However when I use SqlConnection
using (con)
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = #sql;
cmd.ExecuteScalar();
}
}
It fails, it says
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.
I think this is because Visual Studio 2010 and SQL Server uses a different datetime format to each other.
How do I fix this?
Current Code:
string sql = "INSERT INTO Order ([LedgerNumber], [OrderNumber], [OrderDate], [PendingDateTime], [EmailAddress]) VALUES (1, '" + rec.OrderNumber + "', CONVERT(datetime, '" + rec.OrderDate + "', 120), CONVERT(datetime, '" + rec.PendingDateTime + "', 120), '" + rec.EmailAddress + "')";
try
{
SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OrderContext"].ConnectionString);
using (con2)
{con2.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con2;
cmd.CommandText = #sql;
cmd.Parameters.AddWithValue("rec.PendingDateTime", DateTime.Now);
cmd.Parameters.AddWithValue("rec.OrderDate", rec.OrderDate);
cmd.ExecuteScalar();
}
Always use sql-parameters instead of string-concatenation. It prevents you from such issues and - more important - from sql-injection:
string sql = #"INSERT INTO Order ([LedgerNumber], [OrderNumber], [OrderDate], [PendingDateTime], [EmailAddress])
VALUES (1, #OrderNumber, #OrderDate, #PendingDateTime, #EmailAddress)";
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OrderContext"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#OrderNumber", rec.OrderNumber);
cmd.Parameters.AddWithValue("#OrderDate", rec.OrderDate);
cmd.Parameters.AddWithValue("#PendingDateTime", rec.PendingDateTime);
cmd.Parameters.AddWithValue("#EmailAddress", rec.EmailAddress);
con.Open();
cmd.ExecuteNonQuery();
}
You: "if I wasn't using datetime.now and get a datetime from a value entered by user. Say '24/07/2014 10:30' how do I use the AddWithValue to achieve this?"
You have to parse the input to DateTime first. Therefore use DateTime.Parse or DateTime.TryParse, DateTime.ParseExact or DateTime.TryParseExact. The TryParse-methods enable you to check if the input is a valid DateTime.
For example:
DateTime pendingDateTime;
if(!DateTime.TryParse(TxtPendingDateTime.Text, out pendingDateTime))
{
MessageBox.Show("Please enter a valid Pending-Date in the format: yourformat");
return;
}
// here you can go on with the code above