AndyDB
AndyDB

Reputation: 431

Inserting a date to SQLite

I am writing a small app using WPF/C# & SQLITE.

One of the functions inserts a record containing two date/time values into a table.

I want to know if there is a proper way to do this (to ensure that the date/month fields are stored consistently).

I have created an INSERT query that uses parameters alongside date variables (clsVariables.DatActivityEnd = DateTime.Now;).

        String cntnStr = ClsVariables.StrDb;
        var connection = new SQLiteConnection(cntnStr);
        connection.Open();
        using (SQLiteCommand cmd = connection.CreateCommand())
        {
            cmd.CommandText =
                "INSERT INTO tblActivity ([Activity_Category], [Activity_Category_Sub], [Activity_Start], [Activity_End], [Activity_Duration]) VALUES (@ActivityCategory, @ActivityCategorySub, @ActivityStart, @ActivityEnd, @ActivityDuration);";
            cmd.Parameters.Add(new SQLiteParameter("@ActivityCategory", ClsVariables.StrActivityCurrent));
            cmd.Parameters.Add(new SQLiteParameter("@ActivityCategorySub", ClsVariables.StrActivitySubCurrent));
            cmd.Parameters.Add(new SQLiteParameter("@ActivityStart", ClsVariables.DatActivityStart.ToString()));
            cmd.Parameters.Add(new SQLiteParameter("@ActivityEnd", ClsVariables.DatActivityEnd.ToString()));
            cmd.Parameters.Add(new SQLiteParameter("@ActivityDuration", ClsVariables.DblActivityDuration));
            cmd.ExecuteNonQuery();
        }
        connection.Close();

Is there anything else I should do - Thank you?

Upvotes: 4

Views: 9086

Answers (1)

c0d3b34n
c0d3b34n

Reputation: 563

You have to use sql formatted strings:

string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");

Update:

Today I would prefer AddWithValues with Type Safety and without any Conversion:

cmd.Parameters.AddWithValue("@ActivityStart", ClsVariables.DatActivityStart);

Upvotes: 7

Related Questions