Posted By

arpo on 03/26/09


Tagged

mysql


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

umang_nine
vali29


Basic MySql actions


 / Published in: C#
 

  1. using System.Data;
  2. using MySql.Data.MySqlClient;
  3.  
  4. public void dbStuff()
  5. {
  6. String strSQL;
  7. String strConn;
  8. MySqlCommand myCommand;
  9.  
  10. strConn = "SERVER=localhost;" +
  11. "port=3306;" +
  12. "database=mydatabase;" +
  13. "user id=youUName;" +
  14. "password=YourPW;";
  15.  
  16. MySqlConnection myConnection = new MySqlConnection(strConn);
  17.  
  18. //Open connection to DB.
  19. try{myConnection.Open();}
  20. catch (Exception e) { trace(e.ToString()); }
  21.  
  22.  
  23. //Insert data to DB, or what ever you want to do.
  24. strSQL = "INSERT INTO mytable (int_field, text_field, date_field) Values (16, 'Lorum ibsum' , '2012-12-21');";
  25. myCommand = new MySqlCommand(strSQL, myConnection);
  26. myCommand.ExecuteNonQuery();
  27.  
  28.  
  29. //Read data from DB.
  30. try
  31. {
  32. MySqlDataReader myReader = null;
  33. strSQL = "select * from mytable";
  34. myCommand = new MySqlCommand(strSQL, myConnection);
  35. myReader = myCommand.ExecuteReader();
  36. while (myReader.Read())
  37. {
  38. trace(myReader["int_field"].ToString());
  39. trace(myReader["text_field"].ToString());
  40. }
  41. }
  42. catch (Exception e) { trace(e.ToString()); }
  43.  
  44.  
  45. //Close connection to DB.
  46. try {myConnection.Close();}
  47. catch (Exception e) { trace(e.ToString()); }
  48. }
  49.  
  50. public void trace(String s)
  51. {
  52. out1.Text += s + "<br />"; //out1 is a Literal
  53. }

Report this snippet  

You need to login to post a comment.