与sql server的基本连接

时间:2014-03-06 22:29:40

标签: c# sql-server

我已经阅读了很多教程和示例,但仍无法连接到sql server。

我正在使用窗口身份验证和这个简单的代码(剥离以突出显示连接部分)

    SqlConnection myConnection = new SqlConnection(@"Data Source=localhost;Initial Catalog=MyDatabase;Trusted_Connection=True;connection timeout=5");

    try
    {
    myConnection.Open();
    "connected"
    }
    catch(SqlException ex)
    {
    "Send curriculum to mcdonald" + ex.Message
    }

我已经尝试过localhost \ sqlexpress,computername \ sqlexpress和许多其他设置,服务打开,数据库在那里,并且可以从sql server management等进行访问。 这是我第一次尝试使用sql server,所以可能我忘记了一些基本的东西,我必须检查什么以确保它能够正常工作?

1 个答案:

答案 0 :(得分:1)

SqlConnection myConnection = new SqlConnection("Data Source=localhost\\InstanceName;Initial Catalog=MyDatabase;Trusted_Connection=True;connection timeout=5");

OR

SqlConnection myConnection = new SqlConnection("Data Source=.\\InstanceName;Initial Catalog=MyDatabase;Trusted_Connection=True;connection timeout=5");

OR

SqlConnection myConnection = new SqlConnection("Data Source=ServerName\\InstanceName;Initial Catalog=MyDatabase;Trusted_Connection=True;connection timeout=5");

阅读完评论后,试试这个..

SqlConnection myConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=MyDatabase;Trusted_Connection=True;connection timeout=5");