C# - Why doesn't time and date save in mysql database? - c#

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.

Related

insert datetime value gives error "Incorrect syntax near 12"

DateTime myDateTime = Convert.ToDateTime(rd2[0].ToString())
values = myDateTime.ToString("yyyy-MM-dd HH:mm:ss") + " , " + rd2[1].ToString()+ " , " + rd2[2].ToString()+ " , " + rd2[3].ToString()+ " , " + rd2[4].ToString()+ " , " + rd2[5].ToString() ;
i am trying to insert date 2016-04-22 12:58:11 in sql server table of datatype datetime but it gives error "Incorrect syntax near 12"
The string you end up with is similar to this:
2016-04-22 00:00:00,2016-04-22 00:00:00,2016-04-22 00:00:00,2016-04-22 00:00:00
Inserting that into a SQL statement is invalid. You need to wrap each date in single quotes so that you have:
'2016-04-22 00:00:00','2016-04-22 00:00:00','2016-04-22 00:00:00','2016-04-22 00:00:00'
Either way this makes your life difficult and makes your code subject to sql injection and insecure. Consider using parameters like this.
string exampleSQL = "SELECT * from mydatetable where dateOne = #date1 and dateTwo = #date2";
SqlConnection connection = new SqlConnection(/* connection info */);
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("#date1", SqlDbType.DateTime).Value = myDateTime;
command.Parameters.Add("#date2", SqlDbType.DateTime).Value = rd2[1];
This way you dont need to worry about formatting. The system automatically will replace the #date1 and #date2 with the values you specified and it will deal with adding the nescessary structure of the SQL without you having to worry about it.
I strongly suggest using "parametrizing your sql queries"...For example, you can check it out here:
http://www.dreamincode.net/forums/topic/268104-the-right-way-to-query-a-database-parameterizing-your-sql-queries/
Cheers!

I want to update field with "Datetime" datatype in table of my database from DateTimePicker object in C#

Note: Don't care with Connection becuse the connection work.
Field in database is DateTime
DateTime dtc = Convert.ToDateTime(dateTimePicker1.Value.Date);
cmd = new SqlCommand("UPDATE LAB_TESTING set Lab_Nam='" + lab_id + "',Rslt_lb='" +
textBox1.Text + "',Tst_Dat='" + dtc + "' Where Lab_ID='" +
bindex + "'", con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("You Update recored successfully", "delete", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = null;
con.Close();
readdatagrid1();
after Run program , I got Conversion failed when converting date and/or time from character string.
Don't use string concatenation to build your queries (SQL injection alert, also read this!). Use parameterized queries. As for your problem: format the date as yyyy-MM-dd (ISO 8601) and it'll work.
If you'd have used parameterized queries correctly you could've just passed in the DateTime as-is and the driver would've ensured the value would get passed correctly to SQL regardless the "format" / locale setting / whatever since the value would be passed as a DateTime instead of a string. Something like this:
cmd = new SqlCommand(#"UPDATE LAB_TESTING set Lab_Nam = #labnam,
Rslt_lb = #result, Tst_Dat = #tstdat
Where Lab_ID = #id", con);
cmd.Parameters.AddWithValue("#labnam", lab_id );
cmd.Parameters.AddWithValue("#result", textBox1.Text);
cmd.Parameters.AddWithValue("#tstdat", dateTimePicker1.Value.Date);
cmd.Parameters.AddWithValue("#id", bindex);
con.Open();
cmd.ExecuteNonQuery();
Other than that I also recommend to wrap the con and cmd in a using() { ... } statement so that you can be sure this stuff gets disposed properly and that you give your variables and fieldnames decent names and use a consistent naming scheme.
Now repeat after me:
I will never, ever, run queries again that have been string-concatenated together anymore!
From now on I will use parameterized queries
If I need to run string-concatenated queries ever again I will make sure all values are escaped properly
Repeat the above aloud, at least 50 times.
This will work for you.
var date = (DateTime)dateTimePicker1.SelectedDate.Value;
Try this
DateTime dtc = Convert.ToDateTime(dateTimePicker1.Value.ToString("dd/MM/yyyy"));
or else
you can also do this
DateTime dtc = Convert.ToDateTime(dateTimePicker1.Text)
If you are getting this error with your SQL code than have a look here

Converting and comparing mysql and c# datetime

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.

Insert datetime from C# into SQL Server database

when I try to insert datetime value into a SQL Server database I get this error:
Conversion failed when converting date and/or time from character string
Code:
connection.Open();
SqlCommand command = new SqlCommand("insert into table values(#time)", connection);
command.Parameters.AddWithValue("#time", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
Table table has 1 datetime column called time.
Edit:
my table created in msSQL 2012: http://i.imgur.com/TJ3t3y7.png
my real code is:
public void vytvorDotaz(String uzivatel, DateTime cas, String nazev, String dotaz)
{
int id = getMaxID() + 1;
connection.Open();
SqlCommand command = new SqlCommand("insert into otazky values('" + id + "', '" + uzivatel + "', '0','0','0','#cas','" + nazev + "','" + dotaz + "')", connection);
command.Parameters.AddWithValue("#cas", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
}
The actual problem here is that you're writing the parameter inside quotes:
... ,'0','#cas',' ...
^ ^
This will not use #cas as a parameter, you're actually trying to insert the string "#cas" into that column, not the contents of the parameter #cas.
Remove the quotes and that part should work.
Additionally, don't use string concatenation to build up the SQL, use parameters for everything, save you some headache from SQL injection attacks or quotes or whatnot. This is related to the "id", "uzivatel", "nazev", and "dotav" parameters you're using (method parameters that is).
Looks like you need:
insert into table values(#time)
Without the single character quote.
Try System.Data.SqlTypes.SqlDateTime Also when storing dates please consider storing them as UTC to prevent confusion.

Searching database with date

In my windows form, i have one text box where users enters the date in the format 16/02/2013 to search for all the entries on that particular date.
In database i have one column which stores date in this format.16/02/2013 02:47:36 AM.
Can somebody advise me with sql query to extract all the entries from database for that particular date and put it on dataset.
I am using this but it is not working.
public DataSet OrderByDate(string date)
{
// string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Amrit\\Desktop\\Database.accdb ;Persist Security Info=False;";
DataSet dataSet = new DataSet();
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "SELECT Customer.[Title] + SPACE(2) + Customer.[Customer's Name] as CustomerName, Customer.[Customer's Ebayname], Customer.[Email Address], Customer.[Phone Number], Customer.[Address 1] + SPACE(2) +Customer.[Address 2] + SPACE(2) + Customer.[City] + SPACE(2) + Customer.[Post Code]+ SPACE(2) + Customer.[Country] as Address, Customer.[Item Purchased], Customer.[Purchased Date], Customer.[Total Price] FROM Customer WHERE [Purchased Date] LIKE '" + "'" + date + "%'";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
dataAdapter.Fill(dataSet, "Customer");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
oleConn.Close();
}
if (dataSet.Tables.Count <= 0)
return null;
else
return dataSet;
}
In datbase the datetime is stored as Date/Time format.
On the database side, if your datatype is date, you can simply do:
where yourdatefield = #dateIn
If it's a datetime, you do this:
where yourdatefield >= #dateIn
and yourdatefield < the day after #dateIn
Since you are using .net there are a couple of things you need to improve in your application code. First, convert the date string to a DateTime object. Second, convert all the user inputs to parameters.
You may or may not need to enclose the datetime in single quotes in the sql, I dont remember:
DateTime start = DateTime.Parse("16/02/2013").Date;
DateTime end = start.AddDays(1);
string sql = "Select * From Customer WHere PurchasedDate >= {0} and PurchasedDate < {1}";
sql = string.Format(sql, start, end);
Also, this is a quick and dirty method that I wrote up here. It should work, but you REALLY should paramaterize this query.
Passing date values in this way does not work, because default formatted date and time value in .NET is not recognized by your SQL engine.
To pass any data to your query, it is best to always use parameters. Add a parameter to you command string:
string sql = "SELECT * FROM Customer WHERE PurchaseDate = #pdate";
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, connection);
adapter.SelectCommand.Parameters.AddWithValue("pdate", date);
adapter.Fill(dataSet, "Customer");
#pdate in the command text is a parameter. Values for the parameter must be supplied before executing the command, as you see in the example.
You can also use simple string concatenation to fill in your values into your SQL statement, but that's only possible with simple integer or string values, and is generally not recommended because it is subject to SQL injection attack.

Categories

Resources