MySQLに限らないと思うけれど、プログラムからOrder Byの付いたSQLを投げてやる場合、parameterとして渡しても意味が無い。
普通O-R mapperを使わずに、直接SQLを投げる場合、SQLの動的生成などせず、SQL injectionの危険性を低減させる為にparametrized SQLを使うと思う。
using (var connection = new MySqlConnection(ConnectionString)) { connection.Open(); var command = new MySqlCommand("Select Count(*) From user Where id = ?ID;", connection); command.Parameters.AddWithValue("?ID", id); if (Convert.ToInt32(command.ExecuteScalar()) != 0) return true; return false; }
然しOrder By句には此の方法を使っても意味が無い。Order ByはParametersを参照しない。
Parameter in order by clause doesn't order -mysql, C# - Stack Overflow
This is because ORDER BY uses a database identifier (ie, a column, alias or expression). You are passing the value as a parameter.
If you validate the user input against a known set of values (ie, the available columns), you can simply interpolate the value into the query string, eg (very rough)
だから乱暴には、一定の文字列以外が来ない様に保証したうえで、文字列操作で直接突っ込む。
var users = new List<User>(); using (var connection = new MySqlConnection(ConnectionString)) { connection.Open(); MySqlCommand command = connection.CreateCommand(); command.CommandText = string.Format(@"Select name, age From user Where name Like ?SEARCH Or age Like ?SEARCH Order By {0} {1};", orderBy, direction); command.Parameters.AddWithValue("?SEARCH", string.Format("%{0}%", searchWord)); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) users.Add(new User(reader.GetString("name"), reader.GetInt32("age"))); } }
一時間くらい此れが判らずに吐きそうになった。
2
全然関係ない話だが、SQLのLimit句は最後に置かなければならない。Limit句の所で「御前此んな所に置くな」と叫んでくれればいいのだが、Limitの後ろの句で
_人_人_人_人_人_人_
> 突然のsyntax error! <
 ̄∨ ̄∨ ̄∨ ̄∨ ̄∨ ̄∨ ̄
これも一時間くらい原因が判らず吐きそうになった。