目前准备用C#采集网站数据的小程序,使用的数据库为SQLite,这个数据库无需安装,直接可以用动态库的形式进行发布,而且C#调用SQLite也比较方便。下面是我采用WPF显示采集到的部分数据的步骤和写法:
1.首先新建一个WPF core应用工程
2.通过NuGet添加SQLite的库System.Data.SQLite和System.Data.SQLite.Core
3.通过代码连接SQLITE
1 static string DbPath = @"E:\mycsample\Boss\bin\x64\Debug\net5.0-windows"; 2 3 //与指定的数据库(实际上就是一个文件)建立连接 4 private static SQLiteConnection CreateDatabaseConnection(string dbName = null) 5 { 6 if (!string.IsNullOrEmpty(DbPath) && !Directory.Exists(DbPath)) 7 Directory.CreateDirectory(DbPath); 8 dbName = dbName == null ? "mytest.db" : dbName; 9 var dbFilePath = System.IO.Path.Combine(DbPath, dbName); 10 return new SQLiteConnection("DataSource = " + dbFilePath+"; Pooling = true; FailIfMissing = false"); 11 } 12 13 // 使用全局静态变量保存连接 14 private static SQLiteConnection connection = CreateDatabaseConnection(); 15 16 // 判断连接是否处于打开状态 17 private static void Open(SQLiteConnection connection) 18 { 19 if (connection.State != System.Data.ConnectionState.Open) 20 { 21 connection.Open(); 22 } 23 } 24 25 public static void ExecuteNonQuery(string sql) 26 { 27 // 确保连接打开 28 Open(connection); 29 using (var tr = connection.BeginTransaction()) 30 { 31 using (var command = connection.CreateCommand()) 32 { 33 command.CommandText = sql; 34 command.ExecuteNonQuery(); 35 } 36 tr.Commit(); 37 } 38 } 39 40 public static SQLiteDataReader ExecuteQuery(string sql) 41 { 42 // 确保连接打开 43 Open(connection); 44 using (var tr = connection.BeginTransaction()) 45 { 46 using (var command = connection.CreateCommand()) 47 { 48 command.CommandText = sql; 49 // 执行查询会返回一个SQLiteDataReader对象 50 var reader = command.ExecuteReader(); 51 tr.Commit(); 52 return reader; 53 //reader.Read()方法会从读出一行匹配的数据到reader中。注意:是一行数据。 54 //while (reader.Read()) 55 //{ 56 // // 有一系列的Get方法,方法的参数是列数。意思是获取第n列的数据,转成Type返回。 57 // // 比如这里的语句,意思就是:获取第0列的数据,转成int值返回。 58 // var time = reader.GetInt64(0); 59 //} 60 } 61 //tr.Commit(); 62 } 63 } 64 65 public static void DeleteDatabase(string dbName) 66 { 67 var path = System.IO.Path.Combine(DbPath, dbName); 68 connection.Close(); 69 70 // 置空,手动GC,并等待GC完成后执行文件删除。 71 connection = null; 72 GC.Collect(); 73 GC.WaitForPendingFinalizers(); 74 File.Delete(path); 75 }
数据库路径暂时写成固定的,可以换成所在EXE目录下的库。‘
4.界面如下
使用xaml进行界面的调整,使用DataGrid进行动态列的加载datagred的AutoGenerateColumns属性需要设置为"False" ,可以更好的控制显示效果
设置列标题居中显示,定义样式
1 <Style x:Key="ColumnHeaderStyle" TargetType="DataGridColumnHeader"> 2 <Setter Property="HorizontalContentAlignment" Value="Center"/> 3 </Style>
并使用样式
ColumnHeaderStyle="{StaticResource ColumnHeaderStyle}"
定义奇偶行颜色不一样和选中颜色变色
1 <Style TargetType="{x:Type DataGridRow}"> 2 <Style.Triggers> 3 <Trigger Property="ItemsControl.AlternationIndex" Value="0"> 4 <Setter Property="Height" Value="24" /> 5 <Setter Property="Background" Value="#FFE4DDB3" /> 6 </Trigger> 7 <Trigger Property="ItemsControl.AlternationIndex" 8 Value="1"> 9 <Setter Property="Height" Value="24" /> 10 <Setter Property="Background" Value="#FFF2F2F2" /> 11 </Trigger> 12 13 <Trigger Property="IsSelected" 14 Value="True"> 15 <Setter Property="BorderBrush" 16 Value="Blue" /> 17 <Setter Property="BorderThickness" 18 Value="1" /> 19 </Trigger> 20 </Style.Triggers> 21 </Style>
另外URL地址列显示为DataGridHyperlinkColumn,并在左侧显示行的序号
在MainWindow.xmal.cs中写入
1 private void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e) 2 { 3 e.Row.Header = e.Row.GetIndex() + 1; 4 } 5 6 private void dataGrid_UnLoadingRow(object sender, DataGridRowEventArgs e) 7 { 8 dataGrid_LoadingRow(sender, e); 9 if (dataGrid.Items != null) 10 { 11 for (int i = 0; i < dataGrid.Items.Count; i++) 12 { 13 try 14 { 15 DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow; 16 if (row != null) 17 { 18 row.Header = (i + 1).ToString(); 19 } 20 } 21 catch { } 22 } 23 } 24 } 25 26 private void Window_Loaded(object sender, RoutedEventArgs e) 27 { 28 dataGrid.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_LoadingRow); 29 dataGrid.UnloadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_UnLoadingRow); 30 }
显示数据,用于连接SQLITE的数据,取得数据到DATAGRID中进行显示
1 private void button_Click(object sender, RoutedEventArgs e) 2 { 3 SQLiteDataReader sr = ExecuteQuery("select id,title,url from one_level"); 4 if (sr != null) 5 { 6 System.Data.DataTable Dt = new System.Data.DataTable(); 7 Dt.Load(sr); 8 dataGrid.ItemsSource = Dt.DefaultView; 9 } 10 }
运行,效果为: