目前准備用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 }
運行,效果為: