简体   繁体   中英

Reading an SQLite DateTime value from database and assigning it to a C# string variable

I have a database with a datatable which includes a DateTime column among other things. When using SQL server, I could read the DateTime value from the database using the following code:

    SqlCommand getdate = new SqlCommand("SELECT * FROM EMPinfo WHERE id = @employeeId", connect);
                getdate.Parameters.AddWithValue("@employeeId", listViewEmployee.SelectedItems[0].SubItems[2].Text);
                getdate.Connection = connect;
                connect.Open();
                SqlDataReader readList = getdate.ExecuteReader(CommandBehavior.CloseConnection);
                while (readList.Read())
                {
                    lblEmpDob.Text = ((DateTime)readList["dob"]).ToString("d");
                }

After changing the code to run with SQLite:

    SQLiteConnection connect = new SQLiteConnection(@"Data Source=quotevodata.db;");
                SQLiteCommand getlistname = new SQLiteCommand("SELECT * FROM EMPinfo WHERE id = @employeeId", connect);
                getlistname.Parameters.AddWithValue("@employeeId", listViewEmployee.SelectedItems[0].SubItems[2].Text);
                getlistname.Connection = connect;
                connect.Open();
                SQLiteDataReader readList = getlistname.ExecuteReader(CommandBehavior.CloseConnection);
                while (readList.Read())
                {
                     lblEmpDob.Text = ((DateTime)readList["dob"]).ToString("d");

                }

I keep getting the following error: "String was not recognized as a valid datetime."

I've tried different combinations and declaration of variables but it's not working out. What is the correct configuration to read DateTime values out of an SQLite database?

SQLite does not have a built-in DateTime object, but rather stores them as Text, Real, or Int values.

From your error, you can infer that it's outputting as text; Which according to SQLite documentation should be in the format of "YYYY-MM-DD HH:MM:SS.SSS"

There are various ways you could parse this to a DateTime object, but I'll use RegEx:

public static DateTime ConvertToDateTime(string str)
{
    string pattern = @"(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d{3})";
    if (Regex.IsMatch(str, pattern))
    {
        Match match = Regex.Match(str, pattern);
        int year = Convert.ToInt32(match.Groups[1].Value);
        int month = Convert.ToInt32(match.Groups[2].Value);
        int day = Convert.ToInt32(match.Groups[3].Value);
        int hour = Convert.ToInt32(match.Groups[4].Value);
        int minute = Convert.ToInt32(match.Groups[5].Value);
        int second = Convert.ToInt32(match.Groups[6].Value);
        int millisecond = Convert.ToInt32(match.Groups[7].Value);
        return new DateTime(year, month, day, hour, minute, second, millisecond);
    }
    else
    {
        throw new Exception("Unable to parse.");
    }
}

docs: http://www.sqlite.org/datatype3.html

Thanks for the answers, I finally got it to work by changing the INSERT statement to SQLite format as suggested:

    string empDob = dateDOB.Value.ToString("yyyy-MM-dd");
    //I then inserted this string into the database with the column configured as a "DATE" datatype.

After that, I used the following statements to read and format the date to usable string and it worked beautifully:

    DateTime dateOfBirthEmp = DateTime.Parse(readList["dob"].ToString());

    lblEmpDob.Text = dateOfBirthEmp.ToString("d");

I really appreciate the help.

Why do you convert 2 times?

If you have a Date column in SQLite the provider can manged that for you. You can direct insert as DateTime and read as DateTime.

It's feels a bit hacky but this is the only solution I was able to come up with. It just creates a new column, copies all the values in DateTime format to the new column and deletes the old time string column.

DataTable dt = GetDataTable();
string tc = "TimeColumnName";

dt.Constraints.Clear();
int ordinal = dt.Columns[tc].Ordinal;
dt.Columns[tc].ColumnName = "TSOLD";
dt.Columns.Add(tc, typeof(DateTime));
foreach (DataRow row in dt.Rows) row[tc] = Convert.ToDateTime(row["TSOLD"]);
// remove "OLD" column
dt.Columns.Remove("TSOLD");
dt.Columns[tc].SetOrdinal(ordinal);
dt.Constraints.Add(new UniqueConstraint(dt.Columns[tc]));

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