Search code examples
c#phpmyadminlocalhostsqlconnectionsqlexception

SQL connection to localhost


I install DENWER and with help of built-in PhpMyAdmin create a database on localhost. When i connect to database in my C# application i get "SQL Exception was unhandled". Dont understand where is my mistake...

Code:

SqlConnection connection = new SqlConnection("Data Source=localhost; User Id=root; Password=; Initial Catalog=MyDB");
connection.Open();

Solution

  • Since phpMyAdmin is a MySQL administration tool, I assume you've actually installed MySQL. Obviously you should check that you have a database installed and running before you go any further. Can you connect to it in phpMyAdmin or with the mysql command line tools?

    Try installing the MySQL .NET connector, add a reference to the MySql.Data assembly and then:

    var connection = new MySqlConnection(
                   "server=localhost;user id=root;password=secret;database=MyDB;");
    connection.Open();
    

    In general you should wrap your connection, command and data reader objects in using if you can so that they'll get disposed properly

    using(var connection = new MySqlConnection("..."))
    {
        connection.Open();
        using(var command = connection.CreateCommand())
        {
            command.CommandText = "...";
    
        }
    
        connection.Close();
    }
    

    etc. or wrap in a try-finally and clean up the objects in the finally.