亚洲乱色熟女一区二区三区丝袜,天堂√中文最新版在线,亚洲精品乱码久久久久久蜜桃图片,香蕉久久久久久av成人,欧美丰满熟妇bbb久久久

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

【C#】SQLite SELECT 數(shù)據(jù)操作指南

admin
2024年10月20日 0:3 本文熱度 2130

本文將詳細介紹如何使用 C# 在 SQLite 數(shù)據(jù)庫中執(zhí)行 SELECT 操作。SELECT 操作是數(shù)據(jù)庫查詢中最常用和最重要的操作,用于從數(shù)據(jù)庫中檢索數(shù)據(jù)。

準備工作

首先,確保你的項目中已安裝 System.Data.SQLite NuGet 包。在你的 C# 文件頂部添加以下 using 語句:

using System;using System.Data;using System.Data.SQLite;

連接到數(shù)據(jù)庫

在執(zhí)行任何查詢之前,我們需要建立與數(shù)據(jù)庫的連接。以下是一個建立連接的輔助方法:

public static SQLiteConnection ConnectToDatabase(string dbPath){    try    {        SQLiteConnection connection = new SQLiteConnection($"Data Source={dbPath};Version=3;");        connection.Open();        return connection;    }    catch (Exception ex)    {        Console.WriteLine($"連接數(shù)據(jù)庫時出錯:{ex.Message}");        return null;    }}

基本的 SELECT 操作

查詢所有記錄

以下是一個查詢表中所有記錄的方法:

public static void SelectAllRecords(SQLiteConnection connection, string tableName){    try    {        string sql = $"SELECT * FROM {tableName}";        using (SQLiteCommand command = new SQLiteCommand(sql, connection))        {            using (SQLiteDataReader reader = command.ExecuteReader())            {                while (reader.Read())                {                    for (int i = 0; i < reader.FieldCount; i++)                    {                        Console.Write($"{reader.GetName(i)}: {reader[i]}, ");                    }                    Console.WriteLine();                }            }        }    }    catch (Exception ex)    {        Console.WriteLine($"查詢所有記錄時出錯:{ex.Message}");    }}

使用示例:

SelectAllRecords(connection, "Users");

使用條件查詢

以下是一個帶條件的查詢方法:

public static void SelectRecordsWithCondition(SQLiteConnection connection, string tableName, string condition){    try    {        string sql = $"SELECT * FROM {tableName} WHERE {condition}";        using (SQLiteCommand command = new SQLiteCommand(sql, connection))        {            using (SQLiteDataReader reader = command.ExecuteReader())            {                while (reader.Read())                {                    for (int i = 0; i < reader.FieldCount; i++)                    {                        Console.Write($"{reader.GetName(i)}: {reader[i]}, ");                    }                    Console.WriteLine();                }            }        }    }    catch (Exception ex)    {        Console.WriteLine($"條件查詢記錄時出錯:{ex.Message}");    }}

使用示例:

SelectRecordsWithCondition(connection, "Users", "Age > 30");

使用參數(shù)化查詢

為了防止 SQL 注入攻擊并提高性能,我們應(yīng)該使用參數(shù)化查詢:

public static void SelectRecordsWithParameters(SQLiteConnection connection, string tableName, string condition, Dictionary<string, object> parameters){    try    {        string sql = $"SELECT * FROM {tableName} WHERE {condition}";        using (SQLiteCommand command = new SQLiteCommand(sql, connection))        {            foreach (var param in parameters)            {                command.Parameters.AddWithValue(param.Key, param.Value);            }
           using (SQLiteDataReader reader = command.ExecuteReader())            {                while (reader.Read())                {                    for (int i = 0; i < reader.FieldCount; i++)                    {                        Console.Write($"{reader.GetName(i)}: {reader[i]}, ");                    }                    Console.WriteLine();                }            }        }    }    catch (Exception ex)    {        Console.WriteLine($"參數(shù)化查詢記錄時出錯:{ex.Message}");    }}

使用示例:

var parameters = new Dictionary<string, object>{    { "@minAge", 25 },    { "@maxAge", 40 }};SelectRecordsWithParameters(connection, "Users", "Age BETWEEN @minAge AND @maxAge", parameters);

高級 SELECT 操作

使用聚合函數(shù)

SQLite 支持多種聚合函數(shù),如 COUNT, AVG, SUM 等。以下是一個使用聚合函數(shù)的示例:

public static void SelectWithAggregation(SQLiteConnection connection, string tableName, string aggregation){    try    {        string sql = $"SELECT {aggregation} FROM {tableName}";        using (SQLiteCommand command = new SQLiteCommand(sql, connection))        {            object result = command.ExecuteScalar();            Console.WriteLine($"聚合結(jié)果:{result}");        }    }    catch (Exception ex)    {        Console.WriteLine($"執(zhí)行聚合查詢時出錯:{ex.Message}");    }}

使用示例:

SelectWithAggregation(connection, "Users", "AVG(Age)");

使用 ORDER BY 和 LIMIT

以下是一個帶排序和限制結(jié)果數(shù)量的查詢方法:

public static void SelectWithOrderAndLimit(SQLiteConnection connection, string tableName, string orderBy, int limit){    try    {        string sql = $"SELECT * FROM {tableName} ORDER BY {orderBy} LIMIT {limit}";        using (SQLiteCommand command = new SQLiteCommand(sql, connection))        {            using (SQLiteDataReader reader = command.ExecuteReader())            {                while (reader.Read())                {                    for (int i = 0; i < reader.FieldCount; i++)                    {                        Console.Write($"{reader.GetName(i)}: {reader[i]}, ");                    }                    Console.WriteLine();                }            }        }    }    catch (Exception ex)    {        Console.WriteLine($"執(zhí)行排序和限制查詢時出錯:{ex.Message}");    }}

使用示例:

SelectWithOrderAndLimit(connection, "Users", "Age DESC", 5);

使用 JOIN

以下是一個使用 JOIN 的示例方法:

public static void SelectWithJoin(SQLiteConnection connection, string table1, string table2, string joinCondition){    try    {        string sql = $"SELECT * FROM {table1} INNER JOIN {table2} ON {joinCondition}";        using (SQLiteCommand command = new SQLiteCommand(sql, connection))        {            using (SQLiteDataReader reader = command.ExecuteReader())            {                while (reader.Read())                {                    for (int i = 0; i < reader.FieldCount; i++)                    {                        Console.Write($"{reader.GetName(i)}: {reader[i]}, ");                    }                    Console.WriteLine();                }            }        }    }    catch (Exception ex)    {        Console.WriteLine($"執(zhí)行 JOIN 查詢時出錯:{ex.Message}");    }}

使用示例:

SelectWithJoin(connection, "Users", "Orders", "Users.Id = Orders.UserId");

使用 DataTable 存儲結(jié)果

對于需要在內(nèi)存中處理查詢結(jié)果的情況,我們可以使用 DataTable:

public static DataTable SelectToDataTable(SQLiteConnection connection, string sql){    try    {        DataTable dt = new DataTable();        using (SQLiteCommand command = new SQLiteCommand(sql, connection))        {            using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(command))            {                adapter.Fill(dt);            }        }        return dt;    }    catch (Exception ex)    {        Console.WriteLine($"查詢到 DataTable 時出錯:{ex.Message}");        return null;    }}

使用示例:

DataTable dt = SelectToDataTable(connection, "SELECT * FROM Users WHERE Age > 30");foreach (DataRow row in dt.Rows){    foreach (DataColumn col in dt.Columns)    {        Console.Write($"{col.ColumnName}: {row[col]}, ");    }    Console.WriteLine();}

完整示例

以下是一個完整的示例,展示了如何使用上述所有方法:

using System;using System.Collections.Generic;using System.Data;using System.Data.SQLite;
class Program{    static void Main(string[] args)    {        string dbPath = "C:\\example.db";        SQLiteConnection connection = ConnectToDatabase(dbPath);
       if (connection != null)        {            // 查詢所有記錄            Console.WriteLine("所有用戶:");            SelectAllRecords(connection, "Users");
           // 條件查詢            Console.WriteLine("\n30歲以上的用戶:");            SelectRecordsWithCondition(connection, "Users", "Age > 30");
           // 參數(shù)化查詢            Console.WriteLine("\n25到40歲的用戶:");            var parameters = new Dictionary<string, object>            {                { "@minAge", 25 },                { "@maxAge", 40 }            };            SelectRecordsWithParameters(connection, "Users", "Age BETWEEN @minAge AND @maxAge", parameters);
           // 聚合查詢            Console.WriteLine("\n用戶平均年齡:");            SelectWithAggregation(connection, "Users", "AVG(Age)");
           // 排序和限制結(jié)果            Console.WriteLine("\n年齡最大的5個用戶:");            SelectWithOrderAndLimit(connection, "Users", "Age DESC", 5);
           // JOIN 查詢            Console.WriteLine("\n用戶及其訂單:");            SelectWithJoin(connection, "Users", "Orders", "Users.Id = Orders.UserId");
           // 查詢到 DataTable            Console.WriteLine("\n30歲以上的用戶(使用 DataTable):");            DataTable dt = SelectToDataTable(connection, "SELECT * FROM Users WHERE Age > 30");            foreach (DataRow row in dt.Rows)            {                foreach (DataColumn col in dt.Columns)                {                    Console.Write($"{col.ColumnName}: {row[col]}, ");                }                Console.WriteLine();            }
           // 關(guān)閉連接            connection.Close();        }    }
   // 在這里實現(xiàn)所有上述方法}

注意事項

  1. 始終使用參數(shù)化查詢來防止 SQL 注入攻擊。

  2. 對于大型結(jié)果集,考慮使用分頁查詢或流式處理來避免內(nèi)存問題。

  3. 正確處理 NULL 值,特別是在使用聚合函數(shù)時。

  4. 在完成操作后,記得關(guān)閉數(shù)據(jù)庫連接。

  5. 對于頻繁執(zhí)行的查詢,可以考慮使用預(yù)處理語句(prepared statements)來提高性能。


結(jié)論

本文詳細介紹了如何使用 C# 在 SQLite 數(shù)據(jù)庫中執(zhí)行各種 SELECT 操作,包括基本查詢、條件查詢、參數(shù)化查詢、聚合查詢、排序和限制結(jié)果、JOIN 操作以及使用 DataTable 存儲結(jié)果。這些操作覆蓋了大多數(shù)常見的數(shù)據(jù)檢索場景。


該文章在 2024/10/22 12:24:35 編輯過
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點晴ERP是一款針對中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國內(nèi)大量中小企業(yè)的青睞。
點晴PMS碼頭管理系統(tǒng)主要針對港口碼頭集裝箱與散貨日常運作、調(diào)度、堆場、車隊、財務(wù)費用、相關(guān)報表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點,圍繞調(diào)度、堆場作業(yè)而開發(fā)的。集技術(shù)的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點晴WMS倉儲管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質(zhì)期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標(biāo)簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務(wù)都免費,不限功能、不限時間、不限用戶的免費OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved