Pass parameters in MySQL with C#.NET

by cliper Wednesday, June 04, 2008 7:04 PM

 

I’ve been a Participant of asp.net 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;");
            con.Open();
            cmd = new MySqlCommand("insert into MyTable values (null, ?ParName);", con);
            cmd.Parameters.AddWithValue("?ParName", (string)nameStr.Replace("\"", "^"));
            cmd.ExecuteNonQuery();

            con.Close();


Wow! really neat. We cast our value to string and we can even replace strings inside it.


Why not give it a try? Happy coding! Anyway, there’s much you can do with it. I just play dumb.

 

Tags:

.NET | C#

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



About the author

Author's PhotoI enjoy web developing and would like to share my thoughts of it.

Send mailE-mail me

Most comments

Calendar

<<  May 2012  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar