I used to see this question come up often in the MySQL section of the ASP.NET community forums, so I put together a simple example for developers getting started with MySQL Connector/NET.

Parameters let you pass values into a query safely instead of building the SQL string manually. In this example, the goal is to insert a value into a table called MyTable.

Here is the table design from the original post:

The insert statement looks like this:

1
INSERT INTO MyTable VALUES (NULL, ?ParName);

Then the parameter is passed from code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
MySqlConnection con = null;
MySqlCommand cmd = null;
string nameStr = "Sample value passed";

con = new MySqlConnection("server=localhost;database=db_name;uid=user;pwd=password;pooling=false;");
con.Open();
cmd = new MySqlCommand("INSERT INTO MyTable VALUES (NULL, ?ParName);", con);
cmd.Parameters.AddWithValue("?ParName", (string)nameStr.Replace("\"", "^"));
cmd.ExecuteNonQuery();
con.Close();

That is the basic idea. Once you start using parameters consistently, your queries become cleaner, safer, and easier to maintain.