[英]Reading data from Database and then filter data on some condition in C#
我的问题是在代码隐藏(使用查询)中从SQL Server提取数据然后对代码隐藏(C#)的某些参数应用过滤的最佳方法是什么
就像我必须使用动态查询从SQL Server提取数据一样-[TableName]应该按输入传递
Select * From [TableName]
然后我想对结果进行过滤,例如应用有效的日期过滤,isActive或其他任何方法。
string SqlString = "SELECT * FROM TableName;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
DBErLog.DbServLog(se, se.ToString());
}
finally
{
Conn.Close();
}
否则我会用
DataSet ds = new DatSet()
sda.Fill(ds)
如果我们不知道表列(生效日期或IsActive列除外),如何迭代结果集(DataTable / DataSet)并过滤记录
然后创建对象并将结果转换为XML格式的对象。
非常感谢您的帮助。 提前致谢。
正如@Steve在他的评论中提到的,一个好的做法是在SQL查询中尽可能多地进行过滤。
有多种方法可以使用T-sql条件( WHERE
, GROUP BY
, HAVING
等)来过滤和操作数据。 与您可以在应用程序内部执行的操作相比,SQL Server的效率很高。
这是有关此主题的有趣讨论: “永远不要在代码中执行SQL Server不能为您做好的事情”-这是设计不良的良方吗?
另一方面,在特殊情况下,使用sql语句会浪费资源且不必要。 例如,高频GUI的更改和更新,当您遇到这样的情况时,对sql server的多个查询可能会浪费资源,在这种情况下,一种应对方法是从数据表或某个其他对象中提取数据。使用Linq , Lambda表达式 ,二进制搜索等在程序内部缓存...
重要的是要注意,作为程序员,您应该掌握并了解什么是处理数据的最有效方法。
请在代码中查看我的评论/建议:
private void foo()
{
// add a much conditions as you can inside the query
// for example "SELECT * FROM TableName WHERE Col2 IS NOT NULL AND col2 LIKE '%jr%' AND col3 > 3 AND YEAR(col4) = 2017"...
string SqlString = "SELECT * FROM TableName";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
// you can add more conditions, filterring, sorting, grouping using LINQ or Lambda Expretions
// for example create new datatable based on condition
DataTable newDt = dt.AsEnumerable().Where(x => x.Field<int>("col3") > 3).Select(y => y).CopyToDataTable();
// use WriteToXml() method and save as xml file
string FilePath = @"C:\YOUR_FILE_PATH.xml";
// give name to the datatable, WriteToXml() can not create xml with null table name
newDt.TableName = "myTableName";
// save
newDt.WriteXml(FilePath);
}
catch (SqlException se)
{
DBErLog.DbServLog(se, se.ToString());
}
finally
{
Conn.Close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.