Skip to content
Advertisement

How to connect to a mysql database in C# and mimic the SELECT, UPDATE and INSERT functions

How can I connect to a MySQL database in C#, and use it to UPDATE values in the database, INSERT values in the database and SELECT values from the database.

Also, is it possible to get the value of the row, and mimic this PHP in C#?

$query = mysql_query("SELECT * FROM foo WHERE foo = 'foo');
while($row = mysql_fetch_assoc($query)) {
$foo1 = $row['foo1'];
//and so on
}

Advertisement

Answer

You have to download the MySql Connector/.NET.

How to connect to MySQL 5.0 using c# and mysql connector/net! lists some sample code which is quite similar to what you have:

private void button1_Click(object sender, System.EventArgs e)
{
  string MyConString = "SERVER=localhost;" +
                       "DATABASE=mydatabase;" +
                       "UID=testuser;" +
                       "PASSWORD=testpassword;";
  MySqlConnection connection = new MySqlConnection(MyConString);
  MySqlCommand command = connection.CreateCommand();
  MySqlDataReader Reader;
  command.CommandText = "select * from mycustomers";
  connection.Open();
  Reader = command.ExecuteReader();
  while (Reader.Read())
  {
    string thisrow = "";
    for (int i= 0;i<Reader.FieldCount;i++)
      thisrow+=Reader.GetValue(i).ToString() + ",";
    listBox1.Items.Add(thisrow);
  }
  connection.Close();
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement