【问题标题】:Open database into application c#在应用程序c#中打开数据库
【发布时间】:2016-03-14 19:17:29
【问题描述】:

我已将 SQL Server .mdf 数据库文件添加到我的 C# 应用程序,但是当我尝试使用此代码连接时,程序会导致连接错误。

代码:

DataSet data;

string con = "Data Source=dbinterno.mdf;";
string queryString = "Select * FROM Dati";

try
{
    using (SqlConnection connection = new SqlConnection(con))
    {
        connection.Open();
        SqlDataAdapter adapter = new SqlDataAdapter();

        SqlCommand command = new SqlCommand(queryString, connection);

        command.ExecuteNonQuery();

        data = new DataSet();
        adapter.Fill(data);
        MessageBox.Show(data.ToString());

        connection.Close();
    }
}
catch
{
    MessageBox.Show("\n Problemi di connessione al database");
}

错误是:

ERROR IMAGE

【问题讨论】:

  • 我们需要更多信息......初学者有什么错误?
  • 没有明确的信息。我们不知道是什么问题。
  • @trousyt 我有插入错误图片
  • 您是否尝试使用绝对 mdf 文件路径而不是相对路径?
  • 如果这个string con = "Data Source=dbinterno.mdf;"; 是你所有的连接字符串,那么它还没有完成。连接字符串应该是,例如,Server=.\SQLSERVER;Initial Catalog=dbinterno;Integrated Security=True 等等...在 google 中搜索 mssql 服务器中的连接字符串...就像错误所说的 the server not found...,因为它没有在连接字符串中定义。

标签: c#


【解决方案1】:

以下是一些观察:

  1. 您的连接字符串需要修改。尝试使用 string con = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"; 使用 Windows 身份验证或此:
    string con = "Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword;"; 使用标准安全性,来源:connectionstrings.com。除了在代码中,这也应该以其他方式进行管理。桌面应用程序可以反编译,如果密码更改,则需要重新构建。在 ASP.NET 应用程序中,Microsoft advises 使用 web.config 文件或在 Windows 注册表中使用自定义子项。

  2. 您将希望将 ExecuteReader() 用于 SELECT 语句,因为 ExecuteNonQuery() 不会返回结果集。请参阅此answer,它描述了 SQL Server 方法类型的差异

  3. 你不需要connection.Close();,using 语句会处理它。

【讨论】:

  • 您在 1 下的答案。最好向用户展示一些示例,然后链接到某个网站(“明天”可以“关闭”......而且,至少,你必须努力将用户指向特定链接,因为“我们”在谈论 mssql 服务器)并且它不是可能,而是必须并且非常必须;根据 2. 不是可能,而是必须必须,再次...
猜你喜欢
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
  • 2012-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多