开发者

How to insert DateTime in MySql Database using C# code

2/1/2开发者_如何学Go009 5:04:15 AM

I get it from MySQL database and want to feed it in table from other where i get it.

But it not worked in C# but using gui it work.

How i can feed this date to MySQL database using C# code.


If you work with the MySqlCommand class, you should be able to use a DateTime with the following construct:

using (var command = connection.CreateCommand())
{
    command.CommandText = "INSERT INTO table (dateTimeColumn) VALUES (@1)";

    command.Parameters.AddWithValue("@1", DateTime.Now);

    command.ExecuteNonQuery();
}

This should ensure that the date/time is stored correctly.


Simply Do following Code

string dt;   
string dt2;
DateTime date = DateTime.Now;    
DateTime date2 = DateTime.Now;    
dt = date.ToString("yyyy-MM-dd H:mm:ss");  
dt2 = date2.ToString("yyyy-MM-dd H:mm:ss"); 


    string dt;   
    string dt2;
    DateTime date = DateTime.Now;    
    DateTime date2 = DateTime.Now;    
    dt = date.ToLongTimeString();        // display format:  11:45:44 AM
    dt2 = date2.ToShortDateString();     // display format:  5/22/2010

    cmd.Parameters.Add("@time_out", SqlDbType.NVarChar,50).Value = dt;
    cmd.Parameters.Add("@date_out", SqlDbType.NVarChar, 50).Value = dt2;
    cmd.Parameters.Add("@date_time", SqlDbType.NVarChar, 50).Value = string.Concat(dt2, " ", dt); // display format:  11/11/2010 4:58:42


I'm not sure if I know exactly where you are having this problem, but if it's after reading the information from the Database to your C# application you may want to take a look at CultureInfo.

CultureInfo MyCultureInfo = new CultureInfo("en-US");

DateTime date = DateTime.Parse(strDate, MyCultureInfo, DateTimeStyles.NoCurrentDateDefault);

This should allow you to convert '2/1/2009 5:04:15 AM' to a DateTime format.

http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(VS.71).aspx


This will work:

string today_date;   
DateTime date = DateTime.Now;
today_date=date.ToString("yyyy-MM-dd HH:mm:ss");


Just download the sample program here for much easier tutorial. http://jhamnariz.weebly.com/3/archives/05-2012/1.html . Hope it helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜