DateTime problem in sql compact - c#

I'm using Sql Compact3.5 as my DB with C# .NET In different systems i'm getting the datetime format differently. In an Windows XP it's retrieving the datetime in the format : MM-dd-yyyy HH:mm:ss and in Media center it's retrieving in the format : MM/dd/yyyy hh:m:ss. Is there any way to make the datetime format free from culture or can i set the datetime format in sql compact so let it be any PC it'll use that format only???
Example :
//TimeOfCall is passed as String using the format DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss");
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
using (SqlCeCommand SqlceCmd = new SqlCeCommand(
"Insert into myreports(TimeOfCall,Status) values(?,?)", con))
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlceCmd.Parameters.Add(new SqlCeParameter("#TimeOfCall", strTimeOfCall));
SqlceCmd.Parameters.Add(new SqlCeParameter("#Status", strStatus));
int RowsaAffected = SqlceCmd.ExecuteNonQuery();
con.Close();
return RowsaAffected;
}
}
While Rertiving the record the query is used in this way :
//FromTime and ToTime are passeed in the same format as while storing
using (SqlCeConnection con = new SqlCeConnection(ConString))
{
using (SqlCeDataAdapter SqlceDA = new SqlCeDataAdapter("Select TimeOfCall from myreports where TimeOfCall between '" + strFromTime + "' and '" + strToTime + "' order by TimeOfCall", con))
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlceDA.Fill(dtReports);
con.Close();
return dtReports;
}
}
I hope it's clear

Ok, from the code, you're basically doing the right thing the wrong way.
The good news is that you're using parameters - that's exactly right - however you don't need actually don't want to convert the date to a string before setting the parameter value.
Simplest should be to change SqlceCmd.Parameters.Add(new SqlCeParameter("#TimeOfCall", strTimeOfCall)); to SqlceCmd.Parameters.AddWithValue("#TimeOfCall", timeOfCall)); where timeOfCall is a DateTime value.
The same applies to the status if that's not natively a string.
If you want to be more explicit about types create the parameter first defining the type and then set it.
For your selection query do the same thing, replace your string concatenation with parameters #fromTime and #toTime and set the parameters directly from the appropriate DateTime values

Related

in oracle db format of date 04-DEC-20 while displaying in console shows date like 04-09-2020

i need to fetch last modified date of item in table(oracle db).
in db format of modified date=04-DEC-20
while displaying in console modified date=04-09-2020
c# code to fetch modified date
string connString =DBUtils.GetDBConnection();
OracleConnection conn = new OracleConnection();
conn.ConnectionString = connString;
string sql = "select LASTMODIFIED , name from v_vname where name in('hector')";
OracleCommand cmd = new OracleCommand();
// Set connection for command.
cmd.Connection = conn;
cmd.CommandText = sql;
conn.Open();
using (DbDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
int date = reader.GetOrdinal("LASTMODIFIED"); // 0
var LASTmTime = reader.GetValue(0);
Console.WriteLine("modifieddate:" + LASTmTime);
}
}
}
In Oracle, you can format a date as a string with to_char():
select to_char(lastmodified, 'dd-mm-yyyy') as last_modified, name
from v_vname
where name = 'hector'
Side note: name in ('hector') is simpler phrased name = 'hector'.
It's elegant when you use .ToString("dd-MM-yyyy") in C#
while (reader.Read())
{
int date = reader.GetOrdinal("LASTMODIFIED"); // 0
var LASTmTime = reader.GetValue(0).ToString("dd-MM-yyyy");
Console.WriteLine("modifieddate:" + LASTmTime);
}
DATE data-type values in Oracle are binary values consisting of 7-bytes (which are always century, year-of-century, month, day, hour, minute and second).
What you are seeing when you say the format is DD-MON-RR is the user interface you are using formatting the binary value as something that you, the user, will understand and for SQL/Plus (and SQL Developer and others) this will be based on the NLS_DATE_FORMAT session parameter and the default NLS_DATE_FORMAT value depends on which territory you say you are using when you setup the database.
What you need to do, is the output a string representation of the DATE formatted according to your requirements. You can either do this in SQL and use TO_CHAR to format the string:
SELECT TO_CHAR( LASTMODIFIED, 'DD-MM-YYYY' ) AS last_modified,
name
FROM v_vname
WHERE name = 'hector'
Or could do it in C#:
DateTime LASTmTime = reader.GetValue(0);
Console.WriteLine("modifieddate:" + LASTmTime.toString("dd-MM-yyyy"));

Checking if current date exists in database using c#

I have a table which I want to insert data in it only once in a day
and to implement that I want to check if current date already exists in
the database by writing these lines
DateTime date = DateTime.Now;
MySqlCommand cmd = new MySqlCommand("SELECT * FROM `attendances` WHERE
`lecture_id` = '" + lecture_id + "' " +
" AND `date` = '"+date.ToShortDateString()+"' ",con);
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
MessageBox.Show("you can't insert");
else MessageBox.Show("you can insert");
The date is inserted to the database in this format xxxx-xx-xx although using the same method for inserting, and date.ToShortDateString() returns the date in this format
xxxx/x/x .
I checked inserting the date manually in the correct format but that also didn't work, I also tried using the DATE function in sql but that didn't work either.
Just apply format string date = DateTime.Now.ToString("yyyy-MM-dd")
And do not call ToShortDateString() in your SQL query
You also should use SqlParameter as your code is vulnerable for SQL injection attack.
You could also avoid using .NET's DateTime and use MySql's NOW() or UTC_DATE() instead within your query, which may be better; if the region of your code and db reside in different timezones.
i.e.
[...] " AND `date` = DATE(NOW()) ",con);

Add date to sqlserver in yyyy-mm-dd

When i add the lastImportedDate(dd-mm-yyyy) with the following method to the sql server everything is fine. In the database the date is yyyy-mm-dd
But add the lastImportedDate(dd-mm-yyyy) with a different pc on the same server the day and month are switched. In the database the date is yyyy-dd-mm.
internal static void insertSelloutSales(string CustomerID, string type, DateTime lastImported, string periodStart, string periodEnd)
{
// Create SQL connection #connection
SqlConnection sqlConnection1 = new SqlConnection(Connection.connectionString());
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
string periodstartQuery = periodStart;
string periodEndQuery = periodEnd;
// Create query with values and execute query
if (!periodStart.Equals("NULL"))
{
periodstartQuery = " '" + periodStart + "'";
}
if (!periodEnd.Equals("NULL"))
{
periodEndQuery = " '" + periodEnd + "'";
}
cmd.CommandText = "Insert into CarsSellout (CustomerID, type, lastImportedDate, PeriodStart, PeriodEnd) VALUES ('" + CustomerID + "', '" + type + "', '" + lastImported + "', " + periodstartQuery + ", " + periodEndQuery + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
Note that the date settings on the pc's are both set as dd-mm-yyyy.
if you need more info please add a comment.!
What can be the problem in this case?
Do not insert your DateTime values with their string representations. Add your DateTime values directly to your parameterized queries.
SQL Server keeps your DateTime values in a binary format. They didn't have any format or something. What you saw them as yyyy-MM-dd or dd-MM-yyyy are just their textual representations.
Generating different string representations of a DateTime instance for different servers usually because they use different culture settings. But since you didn't show any relevant code that generates your strings, we never know.
Speaking of, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Please read carefully;
Bad habits to kick : choosing the wrong data type
As a best practice, use using statement to dispose your connections and commands automatically instead of calling Close methods manually.
using(var con = new SqlConnection(conString))
using(var cmd = con.CrateCommand())
{
// Define your CommandText with parameterized query.
// Define your parameters and their values. Add them with Add method to your command
// Open your connection
// Execute your query
}

How to INSERT date into SQL database date column using dateTimePicker?

I have a birthdate column of type Date in sql database
And in my application I use a dateTimePicker to get the birth date
But when i am trying to insert the date taken from the dateTimePicker:
I get an error :
Incorrect syntax near '12'
And when I try to debug the code I find that the value taken from the dateTimePicker is
Date = {3/21/2015 12:00:00 AM}
The CODE:
//cmd is sql command
cmd.CommandText="INSERT INTO person (birthdate) VALUES("+dateTimePicker.Value.Date+")";
//con is sql connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
What you really should do is use parameters to avoid SQL injection attacks - and it also frees you from string formatting dates - also a good thing!
//cmd is sql command
cmd.CommandText = "INSERT INTO dbo.Person(birthdate) VALUES(#Birthdate);";
cmd.Parameters.Add("#Birthdate", SqlDbType.Date).Value = dateTimePicker.Value.Date;
//con is sql connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Also, it's a recommend best practice to put your SqlConnection, SqlCommand and SqlDataReader into using(....) { .... } blocks to ensure proper disposal:
string connectionString = ".......";
string query = "INSERT INTO dbo.Person(birthdate) VALUES(#Birthdate);";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("#Birthdate", SqlDbType.Date).Value = dateTimePicker.Value.Date;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
As mentioned before the best practice is to use parameters, but if you really need to use a TSQL statement from source you should use date in the format: yyyymmdd
cmd.CommandText="INSERT INTO person (birthdate) VALUES('"+dateTimePicker.Value.Date.ToString("yyyyMMdd")+"')";
Try including quotes:
cmd.CommandText="INSERT INTO person (birthdate) VALUES('"+dateTimePicker.Value.Date+"')";
I'd recommend using parameters too.
Try this as string format:
cmd.CommandText="INSERT INTO person(birthdate)VALUES('"+dateTimePicker.Value.Date+"')";
dateTimePicker stores values as 1/1/1900 12:00:00 AM so you should use DATETIME if you're trying to store it since DATETIME's format is: YYYY-MM-DD HH:MI:SS.
You can print the dateTimePicker value using
MessageBox.Show(dateTimePicker.Value.ToString());
to see for yourself.

SQL Server date store in c#

I have a query which fetches the information from sql server on datematch.
I have searched a lot about SQL Server date string, I just want to match with the date and get the data from database. Also I am using SQL Server 2005, I want to fetch the date and take the time out of it?
Can anybody help me in that... I am new to C#
Here is my query.
return "select Timein, Timeout from Attendance where E_ID = " + E_ID + " and Date = " + DateTime.Now.ToShortDateString();
use the sql server CONVERT function to convert the input date param to time
Change your query to accommodate any one of the below CONVERT function
SQL query to convert Time format into hh:mm:ss:
select convert(varchar, <<dateparam>>, 108)
SQL query to convert Time format into hh:mi:ss:mmm(24h):
select convert(varchar, <<dateparam>>, 114)
You should always use parameters when querying a database - whether or not SQL injection is possible, it's just plain good practice to use parameters, and it solves some of the thorny how many quotes and which kind do I need here to make it a valid SQL statement questions, too.
So try something like:
string sqlStmt = "SELECT Timein, Timeout FROM dbo.Attendance " +
"WHERE E_ID = #ID AND Date = #Date";
using(SqlConnection conn = new SqlConnection("your-connection-string-here"))
using(SqlCommand cmd = new SqlCommand(sqlStmt, conn))
{
// set up parameters
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = E_ID;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = DateTime.Now.Date;
// open connection, read data, close connection
conn.Open();
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
// read your data
}
rdr.Close();
}
conn.Close();
}

Categories