c# - Using a dictionary to perform basic CRUD operations and getting an sqlite syntax error
问题描述
I'm learning SQL and decided to use a data structure I've never used before, a dictionary, to create some methods to perform basic CRUD operations. The first method that I am working on is a method to delete a person given a table name and a dictionary containing the strings to be used in the SQL statement. Here is the code.
class QueryBuilder
{
public void DeleteMemer(string tableName, Dictionary<string, string> columns)
{
var sqliteCommand = new SQLiteCommand($"delete from '{tableName}' where {columns.Keys} = '{columns.Values}'", connection);
sqliteCommand.ExecuteNonQuery();
}
}
class Program
{
static void Main(string[] args)
{
DBManagerSQLite memes = new DBManagerSQLite("SqliteDataBase.db");
QueryBuilder queryBuilder = new QueryBuilder(memes.connection);
Dictionary<string, string> dict = new Dictionary<string, string>();
//------------------DELETE TEST------------------
dict.Add("Memer", "Ryan");
queryBuilder.DeleteMemer("Memers", dict);
}
}
Edited for clarity. I get a run time error on the sqliteCommand.ExecuteNonQuery() line. I suspect this is because of the dictionary I am using. I previously was using all my CRUD operations with simple strings but decided to change it and use a dictionary. I think I am not understand how to use a dictionary in this way. If I remove the dictionary and just hard code strings, the methods work just fine.
解决方案
- 这可能导致 SQL 注入 - 我建议您使用
SqlParameter
- 当像这样注入时,
{columns.Keys}
将转换为类似的东西System...ICollection
,这绝对不是列名。 - 如果你能澄清这个问题会很好。假设问题是语法错误异常:
您可以遍历键值对来WHERE
为您的查询创建一个子句。
示例(无需消毒!):
var whereClause = string.Join(" OR ", columns.Select(kvp => $"{kvp.Key} = '{kvp.Value}'")); // join with AND to create more restrictive query
var sqliteCommand = new SQLiteCommand($"delete from '{tableName}' where {whereClause}", connection);
更新:
除了问题之外,您为什么尝试那样使用数据库?实现代码优先的 EF 上下文相当容易,并且除了简单性之外,您还将获得对查询的编译时检查。只有当您需要更快的速度时,您才能切换到任何微 ORM 并仔细优化性能关键型查询
推荐阅读
- android - 每次安装 Sceneform 插件后,Android Studio 都会崩溃
- scala - 光滑的“for/yield”-查询不能通过负比较编译
- ssrs-2012 - SSRS 日期表达式调整
- bots - http-param-extended 在 RPA Express 中不起作用
- wpf - 来自更多父母的 WPF ZIndex
- statistics - 线性趋势的概率
- vba - 检查哪个文件打开 VBA
- c# - 使用 ActionFilter 的 ASP.NET Core 日志记录
- charts - 在 charts_flutter 时间序列图表中格式化时间标签以包含 hh:mm:ss
- swift - 您的规范源都不包含满足依赖项的规范