SQL connection to localhost

拟墨画扇 提交于 2019-12-08 12:54:54

问题


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();

回答1:


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.



来源:https://stackoverflow.com/questions/5821954/sql-connection-to-localhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!