【问题标题】:How do I connect to a local Microsoft Sql server 2012 Express database from a C# program?如何从 C# 程序连接到本地 Microsoft Sql server 2012 Express 数据库?
【发布时间】:2012-11-18 05:00:44
【问题描述】:

有人可以帮我修复我的连接字符串吗?我是使用 MS SQL Management Studio 的绝对初学者,但我是一位经验丰富的 C# 程序员。我想弄清楚如何连接到我的 PC 上的本地数据库。我今天刚刚安装了 SQL Server 2012 Express,并创建了一个包含一行数据的表。我正在尝试从 C# 程序访问该表。我一直在寻求调用存储过程(没有参数)的帮助,似乎我做的一切都是正确的,但我收到一个异常错误“找不到存储过程'GetCustomers'。”我也尝试将我的过程名称更改为“dbo.GetCustomers”、“SqlTest.dbo.GetCustomers”和“SqlTest.GetCustomers”,但似乎没有任何效果。显然我没有正确连接到我的数据库。我已经为此工作了 4 个小时,所以是时候停下来寻求帮助了。我认为我所需要的只是一个良好的连接字符串和该过程的正确语法。

        Connect c = new Connect();
        if(c.MakeConnection())
        {
            try
            {
                DataSet data = new DataSet();
                SqlDataAdapter adaptor = new SqlDataAdapter();

                //changed to use stored procedure
                adaptor.SelectCommand = new SqlCommand("GetCustomers", c.MyConnect);
                adaptor.SelectCommand.CommandType = CommandType.StoredProcedure;
                //adaptor.SelectCommand.ExecuteNonQuery();//this throws an exception.
                adaptor.Fill(data);//this throws an exception.
            }
            catch (Exception e)
            {
                Logger.WriteMessage(e.Message);
            }
            finally
            {
                c.CloseConnection();
            }

我的连接类包含以下内容:

string connection = Properties.Settings.Default.DatabaseConnectString;
sqlConnection = new SqlConnection(connection);
sqlConnection.Open();

我试过的连接字符串似乎可以连接:

Server=(localdb)\v11.0;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Integrated Security=true;

我的数据库名称是 SqlTest。我在我的连接字符串中尝试了几种变体,但其中大多数都会引发登录失败异常错误。我验证了我的 Windows 用户 ID 具有数据库的管理员权限。

我尝试过的连接字符串导致登录错误:

Server=(localdb)\v11.0;Initial Catalog=SqlTest;User ID=Raphael\couchpotato;Integrated Security=SSPI;Trusted_Connection=Yes;        
Server=(localdb)\v11.0;Initial Catalog=dbo;User ID=Raphael\couchpotato;Integrated Security=SSPI;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Database=SqlTest;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Database=SqlTest;Integrated Security=true;

【问题讨论】:

    标签: stored-procedures sqlcommand


    【解决方案1】:

    我想我需要的只是睡一觉。 ;-)

    我需要将我的所有 SQL 服务器服务设置为自动。由于某种原因,它们被设置为手动,因此它们没有启动。

    然后,我还需要在我的连接字符串中设置正确的服务器名称。这与启动 SQL Server Management Studio 时用于登录的服务器名称相同。这是一个连接和访问正确的数据库和表的连接字符串:

    Server=RAPHAEL\SQLEXPRESS;Database=SqlTest;Trusted_Connection=Yes;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多