我在我的應用程序中使用SQLite(通過System.Data.SQLite包)。現在所有的插入,查詢等操作,通過使用字符串發送命令,例如做:在C#中處理SQLite - 推進作爲命令傳遞字符串操作
SQLiteCommand command = new SQLiteCommand(comStr, db);
其中comStr - 是一個字符串變量保存命令。
我可以使用其他選項而不是字符串嗎?或者,字符串是從.NET處理SQL查詢時應該使用的正確方法嗎?
問題是,使用字符串可能會相當混亂,例如我有一些用戶可以設置的過濾器。使用字符串操作命令 - 儘管作品 - 讓我感覺非常脆弱:
public string GetFilterString()
{
string fil1 = "";
string fil2 = "";
string fil3 = "";
string fil4 = "";
// filter by time
switch (WithinTimeBtnStatus)
{
case WithinTime.All:
break;
case WithinTime.Hour:
string minusHour = (DateTime.Now - new TimeSpan(0, 1, 0, 0)).ToString("yyyy-MM-dd HH:mm:ss.fff");
fil1 = $" timestamp >= datetime('{minusHour}')";
break;
case WithinTime.Day:
string minusDay = (DateTime.Now - new TimeSpan(1, 0, 0, 0)).ToString("yyyy-MM-dd HH:mm:ss.fff");
fil1 = $" timestamp >= datetime('{minusDay}')";
break;
case WithinTime.Week:
string minusWeek = (DateTime.Now - new TimeSpan(7, 0, 0, 0)).ToString("yyyy-MM-dd HH:mm:ss.fff");
fil1 = $" timestamp >= datetime('{minusWeek}')";
break;
}
// filter by extension
for (int i = 0; i < FilteredExt.Count; i++)
{
fil2 += " ext != '" + FilteredExt[i] + "'";
if (i < FilteredExt.Count - 1)
fil2 += " and";
}
// filter by process
if (_processFilterSelected.ToLower() != "all" && _processFilterSelected != "")
{
fil3 = $" proc == '{_processFilterSelected}'";
}
// filter by File Operation
if (_FileOperationFilterSelected.ToLower() != "all" && _FileOperationFilterSelected != "")
{
FileOperation fo = Converters.StringToFileOperation(_FileOperationFilterSelected);
switch (fo)
{
case FileOperation.Deleted:
fil4 = " oper == 'DELETED'";
break;
case FileOperation.Renamed:
fil4 = " oper == 'RENAMED'";
break;
case FileOperation.Modified:
fil4 = " oper == 'MODIFIED'";
break;
}
}
string fil = "";
var tmp = new[] { fil1, fil2, fil3, fil4 };
foreach (var t in tmp)
{
if (t != "")
{
fil += " and" + t;
}
}
return fil;
}
嗯,至少你可以使用參數啓動。 – Fildor
也許看看SqlCommandBuilder。 – Fildor
我猜他想要使用LINQ。 –