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

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar