从数据库中读取SQLite DateTime值并将其分配给C#字符串变量 [英] Reading an SQLite DateTime value from database and assigning it to a C# string variable

查看:62
本文介绍了从数据库中读取SQLite DateTime值并将其分配给C#字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有数据表的数据库,其中包括一个DateTime列.使用SQL Server时,我可以使用以下代码从数据库中读取DateTime值:

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");
                }

更改代码以与SQLite一起运行后:

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."

我尝试了不同的组合和变量声明,但没有成功.从SQLite数据库读取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?

推荐答案

感谢您的回答,我终于通过将INSERT语句更改为建议的SQLite格式来使它起作用:

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");

我非常感谢您的帮助.

这篇关于从数据库中读取SQLite DateTime值并将其分配给C#字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆