简体   繁体   中英

Insert DateTime from JSON response in MySQL DB using C#

I've searched this for what I feel to be a lot but all the threads appear to be looking to insert he Date Time now, which I am not..

I currently receive a Date Time in the following format:

"Date":"2018-03-03T11:00:00Z"

I'm attempting to insert into a MySQL database where the column data set is DATETIME

I'm using the following INSERT statement:

"INSERT INTO tblname (col1, col2) VALUES (@Name, @Date) ON DUPLICATE KEY UPDATE col1 = @Name";

Supplying the values via the AddWithValue parameter as follows:

Command.Parameters.AddWithValue("@Date", Jo["Results"][x]["Date"]);

This always results in me receiving the following within he database:

0000-00-00 00:00:00

A full modified version (to keep it short) of the code used is below:

using MySql.Data.MySqlClient;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Text;

namespace stackoverflow
{
class forstackoverflow
{
    public static int x = 0;
    public static JObject Jo { get; set; }

    static void Main()
    {

        string apiUrl = "REMOVED URL";
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader readerStream = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            string json = readerStream.ReadToEnd();
            readerStream.Close();
            var Jo = JObject.Parse(json);
            JArray id = (JArray)Jo["Results"];
            for (int x = 0; x < id.Count; x++)
            {
                string sqlstring = "sql already highlighted.";

                MySqlConnection Connection = null;
                const string ConnectionString = @"REMOVED CONNECTION DETAILS";
                Connection = new MySqlConnection(ConnectionString);
                MySqlCommand Command = new MySqlCommand(sqlstring, Connection);

                Command.Parameters.AddWithValue("@Name", (string)Jo["Results"][x]["name"]);
                Command.Parameters.AddWithValue("@Date", (string)Jo["Results"][x]["date"]);

                Connection.Open();
                Command.ExecuteNonQuery();
                Connection.Close();
                Connection.Dispose();

                Console.WriteLine((string)Jo["Results"][x]["name"] + " was inserted or updated in the database.");
            }
        }
    }
  }
}

When I try to insert the DateTime 2018-03-03T11:00:00Z into my database (Which is an actual DATETIME type) I get the following error:

Warning: #1265 Data truncated for column 'date' at row 1

I assume your database is handling this error and just defaulting to 0000-00-00 00:00:00 . MySQL DATETIME needs to be in the format of yyyy-MM-dd HH:mm:ss . That means that if you modify your example and remove the T and Z from it, as well as put a space in between the date and time then you can insert it into your Database.

You can put this in the correct format simply by using:

    var test = "2018-03-03T11:00:00Z";
    test = test.Replace("T", " ").Replace("Z", " ");

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM