6.1.4 使用参数

本教程的这一部分向您展示了如何在 MySQL Connector/NET 应用程序中使用参数。

尽管可以直接从用户输入构建 SQL 查询字符串,但这是不可取的,因为它不能防止输入错误或恶意信息。使用参数更安全,因为它们将仅作为字段数据进行处理。例如,假设以下查询是根据用户输入构建的:

Press CTRL+C to copy
string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent = "+user_continent;

如果字符串user_continent来自文本框控件,则可能无法控制用户输入的字符串。用户输入的字符串可能会产生运行时错误,或者在最坏的情况下实际上会损害系统。使用参数时不可能这样做,因为参数仅被视为字段参数,而不是任意的 SQL 代码片段。

使用用户输入参数编写的相同查询是:

Press CTRL+C to copy
string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent = @Continent";
笔记

该参数前面有一个“@”符号,表示它被视为一个参数。

除了标记参数在查询字符串中的位置外,还需要向 MySqlCommand对象添加参数。以下代码片段说明了这一点:

Press CTRL+C to copy
cmd.Parameters.AddWithValue("@Continent", "North America");

在此示例中,字符串“North America”作为参数值静态提供,但在更实际的示例中,它将来自用户输入控件。

另一个例子说明了完整的过程:

Press CTRL+C to copy
using System; using System.Data; using MySql.Data; using MySql.Data.MySqlClient; public class Tutorial5 { public static void Main() { string connStr = "server=localhost;user=root;database=world;port=3306;password=******"; MySqlConnection conn = new MySqlConnection(connStr); try { Console.WriteLine("Connecting to MySQL..."); conn.Open(); string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent=@Continent"; MySqlCommand cmd = new MySqlCommand(sql, conn); Console.WriteLine("Enter a continent e.g. 'North America', 'Europe': "); string user_input = Console.ReadLine(); cmd.Parameters.AddWithValue("@Continent", user_input); MySqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Console.WriteLine(rdr["Name"]+" --- "+rdr["HeadOfState"]); } rdr.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } conn.Close(); Console.WriteLine("Done."); } }

在本教程的这一部分中,您了解了如何使用参数来使您的代码更安全。