今天我想要回傳所有county為1的資料列,以下是取得符合的DataRow[]方法。
/// <summary>
/// 搜尋符合的DataRow[]
/// </summary>
/// <param name="keyword">keyword value</param>
/// <param name="column">keyword column</param>
/// <param name="dt">要查詢的DataTable</param>
/// <param name="useLike">true 用 like (前後會加上%), false 使用 = </param>
/// <returns>符合的DataRow[]</returns>
private DataRow[] SearchDtList(string keyword, string column, System.Data.DataTable dt, bool useLike)
{
DataRow[] id = null;
string op = useLike == true ? " like '" : " = '";
String likeOP = useLike == true ? "%" : String.Empty;
try
{
var foundAuthors = dt.Select(column + op + likeOP + keyword + likeOP + "'");
if (foundAuthors.Length != 0)
{
id = (foundAuthors);
}
}
catch (Exception e)
{
// Console.Write(e.StackTrace);
}
finally
{
}
return id;
}
這一個是把查詢的資料存進DataTable
private System.Data.DataTable getData(string sql, string ConnectionStr)
{
System.Data.DataTable dt = new System.Data.DataTable();
Npgsql.NpgsqlConnection conn = new Npgsql.NpgsqlConnection(ConnectionStr);
conn.Open();
Npgsql.NpgsqlCommand comm = conn.CreateCommand();
comm.CommandText = sql;
Npgsql.NpgsqlDataReader dr = comm.ExecuteReader();
dt.Load(dr);
return dt;
}
完整用法如下:
System.Data.DataTable dt = getData("select id,county,name from town", "Server=localhost;Port=5432;User Id=postgres;Database=myDB;Password=dbpw;");
DataRow[] list = SearchDtList("1", "county", dt, false);
會得到如下結果
沒有留言:
張貼留言