最近使用C#写上位机,需要显示SQLite数据库中存储的数据,查询了许多资料解决了这个问题,在此记录一下。
界面如下图所示:
![界面](https://img-blog.csdn.net/20160823134450752)
点击查询按钮后根据设置的查询日期,在数据库中查询并显示。
按键的单击事件代码如下:
private void FindButton_Click(object sender, RoutedEventArgs e)
{
DataTable dataTable = new DataTable()
string start = StartYear.Text + '-' + StartMoon.Text + '-' + StartDay.Text + ' ' + StartHour.Text + ':' + StartMin.Text + ':' + StartSec.Text
string end = EndYear.Text + '-' + EndMoon.Text + '-' + EndDay.Text + ' ' + EndHour.Text + ':' + EndMin.Text + ':' + EndSec.Text
cmd.CommandText = string.Format("SELECT * FROM Data where Time between datetime('{0}') and datetime('{1}')", start,end)
SQLiteDataReader dr = cmd.ExecuteReader()
dataTable.Load(dr)
DisplayDataGrid.ItemsSource = dataTable.DefaultView
}
显示所有列数据则应使用“select * from tablename”。
若只查询显示某一列数据则应把“*”替换为该列的名称。
另外,SQLite的DATETIME格式为“yyyy-MM-dd hh:mm:ss”应注意符合格式,否在会出现错误。
对于DataGrid中时间数据的显示格式可以通过如下代码进行设置:
<DataGridTextColumn Header="时间" Binding="{Binding Path=Time, StringFormat='yyyy-MM-dd HH:mm:ss'}" />
并且将DataGrid的AutoGenerateColumns属性设置为False。