简体   繁体   中英

Filehelpers import datetime to sql

I'm using Filehelpers and I'm trying to import a CSV file that contains two Datetime fields (ddMMyyy hh:mm) that I can't upload to my table.

I tried this :

 public class TBAtable
    {
        public string BookingNum;
        public string IdVessel;
        public float Length;
        public float Beam;
        public float SumDraught;
        public int Capacity;
        public float GrossTon;
        public static string Pentry;
        public static string Pdepart;
        public string Berth;

    }

 protected void UploadA(object sender, EventArgs e)
    {

        string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload2.PostedFile.FileName);
        FileUpload2.SaveAs(excelPath);

        SqlServerStorage storage = new SqlServerStorage(typeof(TBFtable), ConfigurationManager.ConnectionStrings["bd"].ConnectionString);


        storage.InsertSqlCallback = new InsertSqlHandler(GetInsertSqlCustA);

        TBAtable[] res = CommonEngine.ReadFile(typeof(TBAtable), excelPath) as TBAtable[];
        storage.InsertRecords(res);

        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Données enregistrées avec succès !')", true);
    }
    protected string GetInsertSqlCustA(object record)
    {
        TBAtable obj = (TBAtable)record;
        CultureInfo enUS = new CultureInfo("en-US");
        DateTime PortEntry = DateTime.ParseExact(TBAtable.Pentry, "dd/MM/yyyy HH:mm:ss.fff", enUS, DateTimeStyles.None);
        DateTime PortDeparture = DateTime.ParseExact(TBAtable.Pdepart, "dd/MM/yyyy HH:mm:ss.fff", enUS, DateTimeStyles.None);


        return String.Format("INSERT INTO TA (BookingNum, IdVessel, Length, Beam, SumDraught,Capacity, GrossTon, PortEntry,PortDeparture,Berth ) " + " VALUES ( '{0}' , '{1}' , '{2}' , '{3}', '{4}' , '{5}' , '{6}', '{7}' , '{8}' , '{9}'  ); ", obj.BookingNum, obj.IdVessel, obj.Length, obj.Beam, obj.SumDraught , obj.Capacity ,obj.GrossTon , PortEntry , PortDeparture , obj.Berth  );

    } 

Basically I changed the DateEntry and DateDeparture fields to strings, then I tried to convert those strings to the proper datetime format so that I could insert those values in my table which is in sqlserver.

I get this error: System.ArgumentNullException .. What do I do ?

Your conversion to DateTime does not handle the situation where TBAtable.Pentry is null.

Use TryParseExact instead. The MSDN documentation is here

DateTime portEntry = DateTime.MinValue;
bool isValidDateTime = DateTime.TryParseExact(null, "dd/MM/yyyy HH:mm:ss.fff", enUS, DateTimeStyles.None, out portEntry);

if (!isValidDateTime)
{
    // throw? log? ignore?
}

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