Skip to content
Advertisement

C# Console Application insert row in MySQL database

I have a console application (in Visual Studio 2013 Ultimate) where I want to insert data in my database.

How do I need to connect and insert data in this application?

The query for my database is:
INSERT INTO test.user (id, name) VALUES (NULL, 'Some name');

The code what I have now is:

namespace myDatabaseApp
    {
    class Program{
        static void Main(string[] args){

            Console.WriteLine("Insert a name into the database:");
            string name = Console.ReadLine();

            //Code for inserting row in database

            Console.WriteLine("You have succesfully inserted the name into the database!");
            Console.ReadLine();

        }
    }
}

I am using my localhost as database, my username is root and I have no password.
I already have installed the MySQL Connector for C#. I don’t know if I need it to use.

Advertisement

Answer

Pasting from: https://zetcode.com/csharp/mysql/

static void Main() 
{
    string cs = @"server=localhost;userid=user12;
        password=34klq*;database=mydb";

    MySqlConnection conn = null;

    try 
    {
      conn = new MySqlConnection(cs);
      conn.Open();

      string stm = "SELECT VERSION()";   
      MySqlCommand cmd = new MySqlCommand(stm, conn);
      string version = Convert.ToString(cmd.ExecuteScalar());
      Console.WriteLine("MySQL version : {0}", version);

    } catch (MySqlException ex) 
    {
      Console.WriteLine("Error: {0}",  ex.ToString());

    } finally 
    {
      
      if (conn != null) 
      {
          conn.Close();
      }

    }
}

Just keep in mind that instead of ExecuteScalar you may also use ExecuteNonQuery (for instert/update/delete etc. commands) and ExecuteReader (for commands that return data, e.g. select commands).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement