Hi there is an program I'm working on and in the diary section I'm having some problems.
while registering the entries I'm using the following code where appdate is the appointment date.
dtpappdate is my datetimepicker.
cmd.Parameters.AddWithValue("?appdate", dtpappdate.Value.ToShortDateString());
the above code works fine and when I make entries. It successfully stores the date into the mysql database.
then When I read from database I want to compare the dates of the entries in the database and my current date on the computer so that it will only display the matched dates to display my to do list.
the following is the code to read and compare but my program gives me an error. telling me I fail converting the data.
DateTime dn = new DateTime();
dn = DateTime.Now;
string constring = "Server=localhost;Database=vetsoft; uid=root;pwd=geyikler88;";
string command = "SELECT * FROM vetsoft.clients ";
try
{
using (MySqlConnection myCon = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand(command, myCon))
{
myCon.Open();
MySqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
if( Convert.ToDateTime( myReader["appdate"].ToString()) == dn)
{
listBox1.Items.Add("İsim: " + myReader["name"].ToString() + " Telefon: " + myReader["phone"].ToString() + " P İsim: " + myReader["pname"].ToString() + " Yaş: " + myReader["age"].ToString() + " Randevu Saati: " + myReader["apptime"].ToString() + " Hastalık: " + myReader["sickness"].ToString() + " Ek Not: " + myReader["eknot"].ToString());
}
}
How can I correctly make the comparison? any help?
You compare that C#'s DateTime.Now == the datetime from the MySQL database. This is unlikely to EVER be true, except by pure dumb luck, since DateTime.Now includes the current time down to the tick.
Presuming you are only interested in matching by date, use DateTime.Today to compare, but the date value in your MySQL database should also be date, so you will need to strip time off of that if you are storing time.
You shouldn't convert dates to string for comparing. If you only want to compare date part of datetime, use Date property, ex:
var appDate = myReader["appdate"] as Datetime;
if (appDate.Date == Datetime.Now.Date) {
// Your code goes here
}
It's also good practice to keep dates in db in UTC. This way you don't have to worry about timezones and summer saving time.
Related
I have the following SqlCommand that inserts a row of data to a SQL Server database table. In particular, the Value column is of datatype DateTime.
When the command is ran, the date format is:
Sep 11 2003 12:00AM
Data when viewing in SQL Server database
However, it needs to be 2003-10-11
When I view it in an application, the date column is blank, but when I change the data directly in the database to match yyyy-mm-dd, the column value is visible in the application.
How do I change the format of the date?
using (SqlConnection connection = new SqlConnection(newConnStr))
{
connection.Open();
string dateOfInterviewQS =
"INSERT INTO PropertyValues(PropertyId, UserId, Value, FriendlyName, LastUpdated, CheckDate) " +
" VALUES(#PropertyId, " + "#UserId, " + "#Value, " +
"#FriendlyName, " + "#LastUpdated, " + "#CheckDate)";
using (var cmd = new SqlCommand(dateOfInterviewQS, connection))
{
SqlParameter date = cmd.Parameters.Add("#Value", SqlDbType.DateTime);
date.Value = DateOfInterview;
cmd.Parameters.AddWithValue("#PropertyId", 2);
cmd.Parameters.AddWithValue("#UserId", newUserId);
cmd.Parameters.AddWithValue("#FriendlyName", DBNull.Value);
cmd.Parameters.AddWithValue("#LastUpdated", DateTime.Now);
cmd.Parameters.AddWithValue("#CheckDate", DateTime.Now);
cmd.ExecuteNonQuery();
}
connection.Close();
}
There are a few things fundamentally wrong here...
Can we stop using AddWithValue() already?
Storing a DateTime value as a string is a bad idea. Store data as data. Then format it for display when you need to display it. A DateTime is natively understood by the system, easily sortable, can be used to perform date calculations, etc. A string is just text. (The format you have is coincidentally sortable, but deliberate management of data is always better than something that coincidentally works.)
Having said that...
You can use .ToString() to format your DateTime. For example:
cmd.Parameters.AddWithValue("#LastUpdated", DateTime.Now.ToString("yyyy-MM-dd"));
Or, if you want single-digit months/days:
cmd.Parameters.AddWithValue("#LastUpdated", DateTime.Now.ToString("yyyy-M-d"));
Basically, since you're storing a string, you need to send the database a string. Not a DateTime.
(But, again, you should be storing a DateTime and formatting it as a string when using it downstream.)
I searched all webs and didn't find any solution for my problem. I am new to c# and stack overflow community but am really stuck in this issue.
I have a button to add date and time separately into a datagridview. While filling the rows i am saving row values in SQL Server but its giving exception Failed to convert parameter value from a Int32 to a DateTime when i send it database.data type in c# and SQL Server is Datetime
Here's the code of adding date and time to datagridview
private void addDateTime2_Click(object sender, EventArgs e)
{
int n = dataGridView2.Rows.Add();
dataGridView2.Rows[n].Cells[0].Value = dateTimePicker9.Value.ToString("dd-MM-yyyy");
dataGridView2.Rows[n].Cells[1].Value = dateTimePicker7.Value.ToString("HH:mm:ss");
}
Here's the code that i insert to database:
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
string StrQuery = "INSERT INTO [dbo].[callRedirect] (ISFsectionId, callRedirectDate, incidentNo, callRedirectTime, callRedirectGrade, callRedirectFName, callRedirectLName, callRedirectSerialNo, callRedirectRemark) VALUES (#ISFsectionId, #callRedirectDate, #incidentNo, #callRedirectTime, '"
+ dataGridView2.Rows[i].Cells["Column12"].Tag + "', '" + dataGridView2.Rows[i].Cells["Column13"].Value + "', '" + dataGridView2.Rows[i].Cells["Column14"].Value + "', '" + dataGridView2.Rows[i].Cells["Column20"].Value + "', '" + dataGridView2.Rows[i].Cells["Column19"].Value + "')";
SqlCommand cmd = cnn.CreateCommand();
cmd.CommandText = StrQuery;
cmd.Parameters.AddWithValue("#incidentNo", textBox4.Text);
cmd.Parameters.AddWithValue("#callRedirectDate", dataGridView2.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#callRedirectTime", dataGridView2.Rows[i].Cells[1].Value);
cmd.Parameters.Add("#ISFsectionId", SqlDbType.DateTime).Value = dataGridView2.Rows[i].Cells["Column11"].Tag;
cmd.Connection = cnn;
cmd.ExecuteNonQuery();
}
The only line that could throw this error is
cmd.Parameters.Add("#ISFsectionId", SqlDbType.DateTime).Value =
dataGridView2.Rows[i].Cells["Column11"].Tag;
I seriously doubt that your ISFsectionId is a datetime. I'm also going to bet that Tag contains an integer.
Also note that your grid contains string values instead of DateTimes. This means that either you use string fields of actual date and time, or that ADO.NET is accidentally able to parse your strings to the underlying type. I say accidentally, because this could break if the code run on a locale with different formatting.
To avoid conversion issues, use date and time types in the database and don't convert them to string when loading them and binding them to the grid. Use the DataGridViewStyle.Format property of each column to specify how you want it to be displayed
I have the following code:
private void saveDT()
{
MySqlConnection myConn = new MySqlConnection(Common.myConnection);
myConn.Open();
string sLastLogin = DateTime.UtcNow.ToString("dd.MM.yyyy HH:mm:ss");
MySqlCommand mySqlCmd = new MySqlCommand("UPDATE ha_system.tblaccounts SET lastlogin='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' WHERE name='" + Common.ActiveUser + "'", myConn);
try
{
mySqlCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Fehler: " + ex.Message);
}
finally
{
}
}
But time and date is only saved after the second login in the database column "lastlogin".
Why? What can I do to fix this?
beside the other comments about avoiding SQL injection, you do not need to get a DateTime value from .NET into the MySQL server, you can use built in function and have a query like this:
"UPDATE ha_system.tblaccounts SET lastlogin=NOW() WHERE ..."
If you write the datetime literal in a valid format, it should work fine.
dd.mm.yyyy hh:mm:ss is not a valid format for a MySQL datetime literal. It's also ambiguous, at any rate. Try yyyy-mm-dd hh:mm:ss, with the appropriate capitalization of H and M in the right places for the function you're using.
http://dev.mysql.com/doc/refman/5.6/en/date-and-time-literals.html
And, seriously, don't build queries by concatenating strings.
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])
I have a problem with my stand alone C#.net application when comes to datetimepicker.
It tooks me weeks and not able to get it solve. I hope you can give me a hand.
I have a [create booking], [Search Booking], and [DB] using ms access.
1) Create booking date using the datetimepicker.
format= short
cmd.CommandText = "insert into booking(cname, bdate, btime, ccontact, sname) Values('" + txt_cname.Text + "','" + **dtp_bdate.Value.Date** + "','" + dtp_btime.Value + "','" + txt_ccontact.Text + "','" + txt_sname.Text + "')";
2) Data store in DB is correct.
Example: 01/10/2011 (it is 1st of October 2011)
3) Search Booking date using the datetimepicker.
format= short
string strSql = String.Format("SELECT * FROM booking WHERE bdate = #{0}#", dtp_search.Value.Date);
When I try to search as in 01/10/2011. It doesn't return the result for me.
But when I try to search as in 10/1/2011, it then appeared the result.
I checked on the DB and confirm the date format is saved as 01/10/2011.
But I don't understand why and how this weird thing happen.
Can any kind man give me a hand?
Truly appreciated in advance.
Thank you,
Gary Yee
Looks like Access allows fixed format dates in sql queries (MM/DD/YYYY). And the date is displayed formatted according to the current culture of the database browser (so you get DD/MM/YYYY). Just use (MM/DD/YYYY) in queries.
"IF" your data is correct, try using parameters instead:
DataTable dt = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM booking WHERE bdate = #bdate", cn))
{
cmd.Parameters.AddWithValue("#bdate", dtp_bdate.Value.Date);
using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd))
oda.Fill(dt);
}
}
Otherwise, try debugging your statement by trying >= or <= for your "WHERE bdate = #bdate" statement to see if that changes the results.