Nik*_*lin 4 .net c# sql datatable
我有一个名为call的数据库表,其中包含call_time,location,emergency_type列,还有三种类型的紧急情况:护理人员,警察和消防员.在Windows窗体中,我创建了CheckBoxes的"医护人员","警察","消防员",我想检索满足用户选择的所有表格列.
我创建了一个函数:
public static DataTable GetHistory(DateTime from, DateTime to, bool paramedics, bool police, bool firefighters)
{
string select =
"SELECT call_time, location, emergency_type where call_time between @from AND @to AND";
if(paramedics)
{
select += " emergency_type = 'paramedics' ";
}
if(paramedics && police)
{
select +=" emergency_type = 'paramedics' OR emergency_type = 'police';
}
...
}
Run Code Online (Sandbox Code Playgroud)
然而这个代码看起来很脏,因为如果有30种紧急情况就会有30个!组合,我会在写所有if语句之前变老.
如果您有很多选项可以选择,如果您分享了检索符合所选搜索条件的数据的练习,我将不胜感激.
谢谢!
好吧,如果你必须使用emergency_type作为字符串,那么你可以发送一个包含紧急类型的文本表示的List,而不是传入bool.例如,要调整上面的代码,您可以将方法签名更改为
public static DataTable GetHistory(DateTime from, DateTime to, List<string> types)
{
..
}
Run Code Online (Sandbox Code Playgroud)
然后传入一个看起来像这样的列表(例如)
List<string> types =
new List<string> { "paramedics" };
or
List<string> types =
new List<string> { "paramedics", "police" };
Run Code Online (Sandbox Code Playgroud)
然后,您可以调整查询以在where子句中使用SQL IN语句.接下来将字符串列表转换为逗号分隔的字符串
string values = "'paramedics', 'police'"
Run Code Online (Sandbox Code Playgroud)
创建values变量的一种简单方法是使用
string values = string.Empty;
types.ForEach(s =>
{
if (!string.IsNullOrEmpty(values))
values += ",";
values += string.Format("'{0}'", s);
});
Run Code Online (Sandbox Code Playgroud)
顺便说一下,您可以使用参数化命令来避免SQL注入.一旦你有了字符串,你就可以做到
string select =
"SELECT call_time, location, emergency_type where call_time between @from AND @to AND emergency_type IN " + values
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
341 次 |
| 最近记录: |