如何在system.data.sqlite中转义字符串?

Fre*_*red 2 c# sqlite system.data.sqlite .net-4.5

我正在执行一个SQL查询(system.data.SQLite),如下所示:

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

颜色变量是用户提供的文本.如何逃避此文本以防止SQL注入?或者这是一种不好的做法,我应该以一种完全不同的"受保护"方式执行查询?

Ala*_*ell 5

您应该使用参数化查询:

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

你也可以将一个SQLiteParameters 数组传递给command.Parameters集合,如下所示:

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