Pass parameters in MySQL with C#.NET

I’ve been a Participant of community forum for a while. I’ve been active in the MySQL forum and most developers keep asking the same question. I just thought this might help those new to MySQL connector.NET

Well parameters are variables that can hold values within your query strings. This enables us to pass values in our current query or from one statement to another.

Let’s just go to the point. What we have here is a table named MyTable.


And we have our insert statement as

            INSERT INTO MyTable VALUES (null, ?ParName);

Now, what we want is to pass a value from ?ParName param. Let’s do the coding…
Assuming that we already set everything then our code might look like this…

            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;");
            cmd = new MySqlCommand("insert into MyTable values (null, ?ParName);", con);
            cmd.Parameters.AddWithValue("?ParName", (string)nameStr.Replace("\"", "^"));


Wow! really neat. We cast our value to string and we can even replace strings inside it.
Anyway, there’s much you can do with it. I just play dumb.  Why not give it a try? Happy coding!


Leave a Reply