如何在system.data.sqlite中转义字符串? [英] How to escape a string in system.data.sqlite?

查看:99
本文介绍了如何在system.data.sqlite中转义字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样执行一个SQL查询(system.data.SQLite):

I am executing an SQL query (system.data.SQLite) like so:

var color = "red";
var command = new SQLiteCommand("SELECT something FROM tabletop WHERE color = '" + color + "'", Connection);
var reader = command.ExecuteReader();

颜色变量是用户提供的文本。
如何转义此文本以防止SQL注入?
还是这种不好的做法,我应该以完全不同的受保护方式执行查询吗?

The color variable is a text supplied by the user. How can I escape this text to prevent SQL injection? Or is this bad practice and I should execute the query in some entirely different "protected" way?

推荐答案

您应该使用参数化查询:

You should use parameterized queries:

var command = new SQLiteCommand("SELECT something FROM tabletop WHERE color = @Color", Connection);
command.Parameters.AddWithValue("Color", color);

您还可以传递 SQLiteParameter 的数组放入 command.Parameters 集合,如下所示:

You can also pass an array of SQLiteParameters into the command.Parameters collection like so:

SQLiteParameter[] parameters = { new SQLiteParameter("Color", color), new SQLiteParameter("Size", size) }; // etc.
command.Parameters.AddRange(parameters);

这篇关于如何在system.data.sqlite中转义字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆