I develop an application in .Net C# that retrieves and insert data in a MySQL database.
To establish the connection I use MySqlConnection...
Inside my database, there is several tables each containing multiple date columns in format (yyyy-mm-dd hh: mm: ss)
My problem is that when I get columns by SQL request, my dates are in format (dd-mm-yyyy hh:mm:ss).
I could use the DateFormat() to format the columns, but there are a lot of columns date, and the request can change.
I would like to know if there is a way to impose a date format in the string MyConnection or something like that.
My string is:
string MyConnection = "datasource=192.168.0.1;port=3306;username=" + this.textBoxLogin.Text.ToString().Trim() +
";password=" + this.textBoxPassword.Text.ToString().Trim() + ";AllowZeroDateTime=True;TreatTinyAsBoolean=False;";
Queries + Getting Data + insertion in .xls file:
MySqlConnection conn = new MySqlConnection(MyConnection);
MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
conn.Open();
dataAdapter.SelectCommand = new MySqlCommand("Select * From table;", conn);
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
////get data
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
////insert in .xls File
DataSet dataSet = new DataSet();
dataSet.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dataSet.Tables.Add(dataTable);
CreateWorkbook("test\\Export.xls", dataSet);
Date format in Database: 2015/02/25 13:28:25
Date format in my .xls file: 25/02/2015 13:28:25
If the database stores the data in a date, datetime or timestamp data type, .NET will put that in a DateTime struct. This is perfectly fine since this is just the structure of the data, not the visual representation of it.
If you want to change the default date format of your program (which fixes it once for all for all dates), you can set the CurrentCulture to a culture that you require:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
If you just need to set the date format, you can set Thread.CurrentThread.CurrentCulture.DateTimeFormat and Thread.CurrentThread.CurrentUICulture.DateTimeFormat.
Related
I am writing a program to interact with MSSQLLocal DB using C# through winforms but I find a problem witht the default datetime, it is not the date time format we use in my countr, I wonder how could I through Sql client -sql default C# classes I could change the default date format for a database or All the existing databases?
this could let me to format the datetime https://learn.microsoft.com/en-us/sql/t-sql/statements/set-dateformat-transact-sql?view=sql-server-ver15
but this doesnt change the default dateformat, how can i change programatically the DB datetime default format?
some code example
var connectionstr = $#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog={DBname};Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
var con = new SqlConnection(connectionstr);
con.Open();
string changeDate = $#"SET DATEFORMAT dmy;";
SqlCommand command = new SqlCommand(changeDate , con);
var res = command.ExecuteNonQuery();
SqlCommand cmd = new SqlCommand(InsertCmd, con);
SqlDataAdapter adapter = new SqlDataAdapter() { InsertCommand = cmd };
adapter.InsertCommand.ExecuteNonQuery();
adapter.Dispose();
con.Close();
con.Dispose();
cmd.Dispose();
command.Dispose();
The datetime object in the database is just a datetime, the data can be set to a certain format when displaying in WinForm if you require it. For example, if i wanted the datetime to be display in the UK format:
DateTime.Now.ToString("dd/MM/yyyy")
Datetime Format
Turns out before adding a new value to the row you would need to include in the string CAST(01/01/2020) as dateformat
string command = "select x,y,z,t,ModifiedDate " +
" from ZZ where PP='" + XX + "' and Type='" + YY + "' order by ModifiedDate";
connection();
SqlCommand command = new SqlCommand(command, con);
command.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
ModifiedDate is a DateTime - in SQL i see "2019-07-23 12:02:35.283"
But when i want to see "dt" in C# i only see "2019-07-23"
how can i see full time with minutes and seconds?
The type of the column in the DataTable is DateTime. ZZ is a table.
You could try setting the row to something like this:
((DateTime)row[0]).ToString("yyyy-MM-dd HH:mm:ss")
Like how you said in the comments just add the formatting to your ToString() when assigning to the variable.
What you had shouldn't even compile, since you can't declare both a string and an SqlCommand object with the same name in the same scope. Run the query like this:
string sql = #"
select x,y,z,t,ModifiedDate
from ZZ
where PP= #XX and Type= #YY
order by ModifiedDate";
DataTable dt = new DataTable();
// .Net connection pooling means you really do want a new connection object most of the time. Don't try to re-use it!
// The "using" blocks make sure your objects are closed and disposed, even if an exception is thrown
using (var con = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, con))
using (var da = new SqlDataAdapter(cmd))
{
//use the actual column types and lengths from your database here
cmd.Parameters.Add("#XX", SqlDbType.NVarChar, 30).Value = XX;
cmd.Parameters.Add("#YY", SqlDbType.NVarChar, 10).Value = YY;
da.Fill(dt);
}
But this still won't fix everything. It's mainly about closing the huge gaping-wide security hole and potential denial-of-service issue in the original code.
The actual issue from the question is in a different place than this code. The time portion of your ModifiedDate column is in the resulting DataTable. Really. I promise. If you don't see it, it's because of a DataView, format string, or other issue at the point where you try to observe or display these results.
There is no Date class in C# - even DateTime.Date() returns another DateTime object with an all zeros time component.
Your problem sounds very much like a Regional Settings issue, or more specifically, CultureInfo in C#. Your default (or "current" as applied by Thread.CurrentThread's CurrentCulture or CurrentUICulture) has its CultureInfo.DateTimeFormat setup to supply date-without-time formatting.
Probably the FullDateTimePattern is set to "yyyy-mm-dd" or something equivalent.
I am having an application that shows date and time in datagridview after exporting data from database to dataset.
Details : I have a column called Date that contains date and time in datetime2 format and when showing date, seconds don't show up.
con = new SqlConnection();
con.ConnectionString = my_connection_string;
con.Open();
adap = new SqlDataAdapter("SELECT Date,Object,ASDU,IOA,Alarm from Alarms_List",my_connection_string);
ds = new System.Data.DataSet();
adap.Fill(ds, "Alarms_List");
dataGridView1.DataSource = ds.Tables[0];
Example : Date table contains 15/07/2016 10:03:13
It's shown as : 15/07/2016 10:03
I have also tried CAST(Date AS DATETIME2) in the select statement but none of them works
You must set the "Format", sample like this :
dataGridView1.Columns[0].DefaultCellStyle.Format = "dd.MM.yyyy HH:mm:ss";
use :
select CONVERT(varchar(19), dateColumnName, 120) from tableName;
update:
You may also use the FORMAT function from SQL Server 2012 onwards as below:
select FORMAT(dateColumnName, date-format) from tableName;
ex
select FORMAT(GETDATE(), "dd/MM/yyyy hh:mm:ss");
I have 2 datetimepickers. In my select query i want to fetch records between these dates. datatype for date in database in varchar(MAX). For datetimepicker i have set custom format as dd-MM-yyyy. Here is my sql query
SqlDataAdapter da = new SqlDataAdapter("Select custname From tb_customer WHERE date >= '"+dtp_fromdate.Text+"' AND date <= '"+dtp_todate.Text+"'", con);
For eg: if my start date is 9-06-2012 and to date is 11-06-2012. With the above query it shows me record for 10-06-2012 and 11-06-2012
Incase if my start date is 10-06-2012 and to date is 11-06-2012. With the above query it shows me record for 10-06-2012 and not 11-06-2012
Please help
Use Convert or Cast T-SQL to convert VARCHAR value to Date or DateTime and also learn/use parameters instead of hard-coded SQL string.
The problem lies in lack of use of parameters. Using parameters will avoid any minsunderstanding between you and yuor database backend
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlDataAdapter da = new SqlDataAdapter();
string query = "Select custname From tb_customer WHERE date >= #from AND date <= #to"
da.SelectCommand = new SqlCommand(queryString, con);
da.SelectCommand.AddWithValue("#from" , dtp_fromdate.Value);
da.SelectCommand.AddWithValue("#to" , dtp_to.Value);
da.Fill(ds);
return ds;
}
In excel sheet i have date in format dd.MM.yyyy 16.10.2011 (16 as dd, 10 as MM). When i'm importing data from excel to SQL Server 2008 i get MM.dd.yyyy but still 16.10.2011 (16 as MM, 10 as dd). That's not correct. I found solution on this: go to SQL Server 2008 -> Security -> logins -> {user properties} -> and change default language for user. With this solution i get in SQL Server 2008 dd.MM.yyyy 16.10.2011 (16 as dd, 10 as MM). Is there any other way to convert date in dd.MM.yyyy format without changing user language?
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\JantarV7Export.xlsx;Extended Properties=Excel 8.0";
OleDbConnection olecon = new OleDbConnection(sConnectionString);
olecon.Open();
OleDbCommand cmd = olecon.CreateCommand();
cmd.CommandText = "SELECT person_id, date_of_hours, number_of_hours FROM [Sheet1$]";
OleDbDataAdapter oda = new OleDbDataAdapter(cmd);
OleDbDataReader odr = cmd.ExecuteReader();
conn.Open();
while (odr.Read())
{
SqlCommand cmd1 = conn.CreateCommand();
cmd1.CommandText = "INSERT INTO test_data values (newid(),'" + odr[0] + "',#date_of_hours,'" + odr[2] + "')";
cmd1.Parameters.Add("#date_of_hours", SqlDbType.DateTime).Value =odr[1];
}
cmd1.ExecuteNonQuery();
olecon.Close();
conn.Close();
I think that problem is when i'm inserting into test_data datatable. So i probably should convert dates somehow before inserting. What do you suggest? Thanks. Is there any options like this:
cmd1.CommandText = "INSERT INTO test_data values (newid(),'" + odr[0] +
"',CONVERT(VARCHAR(20),#date_of_hours,104),'" + odr[2] + "')";
cmd1.Parameters.Add("#date_of_hours", SqlDbType.DateTime).Value =odr[1];
(this doesn't work because of CONVERT in insert, but is there some similar solution) or
CONVERT(VARCHAR(20),#date_of_hours,104) AS [DD:MM:YYYY]
UPDATE
In other form i read data through combobox. It shows 1.10.2011, 2.10.2011, .... to 16.10.2011.
da_test_data = new SqlDataAdapter("SELECT test_data_id, date_of_hours, number_of_hours FROM test_data WHERE _person_id= '" + person_id_person + "' ORDER BY date_of_hours", conn);
dt_test_data = new DataTable();
da_test_data.Fill(dt_test_data);
cb_datum.DataSource = dt_test_data.DefaultView;
cb_datum.ValueMember = "test_data_id";
cb_datum.DisplayMember = "date_of_hours";
And combobox for projects:
private void cb_datum_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView drvProjekt = cb_datum.SelectedItem as DataRowView;
if (drvProjekt != null)
{
string date1 = drvProjekt["date_of_hours"].ToString();
DateTime date2 = new DateTime();
date2 =Convert.ToDateTime(date1);
//DateTime date = DateTime.ParseExact(date1, "MMddyyyy hh:mm:ss", null);
//DateTime date = DateTime.ParseExact(date1, "dd.MM.yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
//object obj = DateTime.ParseExact(dddd, "MM/dd/yyyy hh:mm", null);
conn = new SqlConnection(connectionString);
conn.Open();
da_projekt = new SqlDataAdapter("SELECT projekt_id, name_of_projekt, date_of_start, date_of_end FROM projekt WHERE date_of_start < '" + date2 + "' AND date_of_end > '" + date2 + "' ", conn);
dt_projekt = new DataTable();
da_projekt.Fill(dt_projekt);
cb_projekt_id.DataSource = dt_projekt.DefaultView;
cb_projekt_id.ValueMember = "projekt_id";
cb_projekt_id.DisplayMember = "name_of_projekt";
conn.Close();
}
}
When i select 13.10.2011 i get error. Date is recognised as MM.dd.yyyy. I tried everything (all in comments and many more). Yust don't find a solution.
As I mentioned in the comment. your date value is stored as Date in SQL. So when you store date in SQL it will remain date only, and when you retrieve it you will get date object directly. In SQL, it might be displayed as MM.dd.yyyy it doesn't matter.
When you will read this data from SQL, you will get DateTime object, on this if you do .ToString("dd.MM.yyyy", CultureInfo.InvariantCulture) you will get in dd.MM.yyyy format. You can use any format on DateTime object, read more about it on MSDN.
Hope this answers your question.
If possible, just replace "." with "/" in the excel file and format the cell as dd/mmm/yyyy
Excel natively keeps dates as days since some date I do not remember as a floating point value. The important thing is that this matches DateTime.ToOADate().
We read dates from excel files as a floating point value and then use DateTime.ToOADate().
You use CONVERT the wrong way. Database-side, you convert a datetime to a string (varchar), and then you have to rely on build-in type conversions to get a datetime again. You should do it the other way around. If in c# you convert the datetime to a string with a specified format and convert it to a datetime with a matching style database-side nothing can go wrong.
When you use CONVERT the date part should match the style you use (in your case 104). Use this in your sql:
CONVERT(DATETIME, #date_of_hours, 104)
and
cmd1.Parameters.Add("#date_of_hours", SqlDbType.NVarChar).Value =
string.Format("{0:dd.MM.yyyy}", odr[1])