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

查看:25
本文介绍了如何转义 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天全站免登陆