从Visual Studio连接到SQL Server Express

3
我安装了带有Visual Studio 2010的SQL Server 2008,我下载了一个项目,该项目具有在Visual Studio项目本身中创建的数据库文件,现在我想连接到该数据库。
我尝试更改连接字符串,但无法连接到数据库。
有人能告诉我如何连接到数据库吗?我在我的机器上安装了SQL Server 2008(10.0.1600.22)
更新后的连接字符串:
这是我正在使用的连接字符串:
Data Source=SQLEXPRESS\;Initial Catalog=INVENTORY;uid=xxx;pwd=xxx

其中xxx\xxx是我的计算机名称以及我安装的SQL Server实例名称。


1
你能让我们看一下你的连接字符串吗? - Freddie Fabregas
1
你尝试了什么,出现了什么错误?没有适当的信息,没有人能够给出正确的答案。所以请展示你的努力。 - 4b0
1
应该是 Data Source=machinename\SQLEXPRESS 吗? - Freddie Fabregas
1
是的,他应该尝试使用数据源=(local)\SQLExpress。 - Mike C.
服务器=我的服务器名称\我的实例名称;数据库=我的数据库;用户ID=我的用户名; 密码=我的密码; - Habib Zare
显示剩余17条评论
2个回答

5
你正在使用C#吗? 试试这个:
using namespace System.Data.SqlClient;

SqlConnection con = new SqlConnection("Data source = [ip]; Initial catalog = [db name]; User id = [user name]; password = [password]");

con.Open();

在con.Open()处设置一个断点,如果它成功并通过了这行代码,那就意味着你已经成功连接到数据库。

之后,你可能想执行一条 SQL 命令,请尝试以下方法:

    SqlCommand cmd = new SqlCommand("[command]", con);

        // if the command has no return value
        cmd.ExecuteNonQuery();
        //else you might want a Sql data reader to read the return value
        SqlDataReader read = cmd.ExecuteReader();
        while(read.Read())
    {
//do something
    }

1
很好!但是,SqlConnection应该是con = ...而不是SqlConncetion con = ...,并且应该是.ExecuteReader();而不是.ExcuteReader();。请检查您的打字。 - Hernaldo Gonzalez

1
要连接到在SQL Server中创建的数据库文件,请在Visual Studio中打开web.config文件并执行以下操作:
  1. <configuration>标签内打开一个<connectionString>标签。
  2. 将以下内容粘贴到<connectionString>标签之间。

<add name="NameofConnectionString" connectionString="server=YourServerInstanceName; database=DatabaseName; integrated security=SSPI" providerName="System.Data.SqlClient"/>

  1. 刷新 Visual Studio 中的服务器资源管理器,以连接到数据库。

希望这可以帮到您!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接