【问题标题】:how use attachdbfilename in visual studio c#, to acces in my database.mdf如何在 Visual Studio C# 中使用 attachdbfilename 来访问我的 database.mdf
【发布时间】:2016-07-18 20:31:36
【问题描述】:

我使用此链接连接到我在 Visual Studio "c#" 中的数据库

 SqlConnection direction = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\ira\Desktop\hiver 2016\mecatronique\CGC-DOMOTICS\CGC-DOMOTICS\BaseDeDonnées\BDD.mdf ;Integrated Security=True");

但是如果我在另一个桌面上使用我的程序,我会得到一个错误。

我需要帮助,我的错误在于访问我的数据库的链接。

【问题讨论】:

  • 您的代码连接到本地数据库。从逻辑上讲,如果您使用另一台计算机,则本地数据库不存在(除非您将其放在完全相同的位置),因此您将收到错误
  • 是的,我知道,但是如何使用相对路径或绝对路径。我想给他一条全球路径。
  • 那么为什么要使用 mdf 数据库呢? SQL Server Express 上的 SQL 数据库实例会不会更好?
  • 在这种情况下,这是stackoverflow.com/questions/9193746/…stackoverflow.com/questions/29355332/… 的副本,简短的回答是你不能

标签: c# sql-server wpf visual-studio


【解决方案1】:

使用如下所示的数据目录。对于 Web 应用程序,这将是 App_Data 文件夹,对于 Windows 窗体,它将是用户应用程序数据目录

 SqlConnection direction = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|BDD.mdf ;Integrated Security=True");

【讨论】:

  • 我将此数据库用于桌面应用程序。你的代码给出了这个结果:` Une exception non gérée du type 'System.Data.SqlClient.SqlException' s'est produite dans System.Data.dll` Informations supplémentaires : An attempt to attach an auto-named database for file C:\Users\ira\Desktop\hiver 2016\mecatronique\CGC-DOMOTICS\CGC-DOMOTICS\bin\Debug\BDD.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share
  • 如果您在另一台机器上安装应用程序时使用数据目录,则需要使用 clickonce 发布项目将此文件放在 applicationdata 文件夹中。
【解决方案2】:

你可以试试 "AttachDbFilename="+Application.StartupPath+"\BaseDeDonnes\BDD.mdf"

【讨论】:

  • `重力代码描述 Projet Fichier Ligne Source État de la suppression Erreur CS0117 'Application' ne contient pas de définition pour 'StartupPath' `
  • 你可以在 wpf 中使用 'System.Reflection.Assembly.GetExecutingAssembly().Location' 而不是 Application.StartupPath
猜你喜欢
  • 2017-03-20
  • 1970-01-01
  • 1970-01-01
  • 2016-10-23
  • 1970-01-01
  • 1970-01-01
  • 2013-01-14
  • 1970-01-01
  • 2011-11-14
相关资源
最近更新 更多