C# and MySql : SELECT , UPDATE , DELETE

Leave a Comment

To Execute Some MySql Statements:
SELECT:
       
  
 //This is the simple code of executing MySql Commands in C#
String cmdText = "SELECT id,name,contact FROM myTable"; //This line is the MySql Command
MySqlCommand cmd = new MySqlCommand(cmdText, con);
cmd.ExecuteNonQuery(); //Execute the command
       
 

UPDATE:
       
  
 //example on how to use UPDATE
cmd = new MySqlCommand("UPDATE ab_data SET banned_from='" + from + "' , banned_until='" + until + "' WHERE name='" + name + "'", con);
cmd.ExecuteNonQuery();
       
 

DELETE:
       
  
 //example on how to use DELETE
cmd = new MySqlCommand("DELETE FROM tbName WHERE colName = someValue",con);
cmd.ExecuteNonQuery();
       
 

*Note: before executing some Sql statements or accessing/manipulating the database, make sure that the connection to the MySql Database server is opened via con.Open(); Remember also to safely close it using con.Close();

Accessing the MySql database is made easier in .NET using MySQL Connector/NET. It should be installed in your system and should be an added reference in your project. Also, Do not forget to import or use it in your code using the statement in C#:
 
       
  
 using MySql.Data.MySqlClient;
       
 

Attached is a sample project that you may try and learn from it.
Attached File  CSharpMySql.rar   23.21KB  

Questions and Comments are welcome!
Thanks!

0 comments:

Post a Comment