C#数据库连接SQL
问题描述:
我试图让它可以使用程序,我把文件夹放在哪里,因此它不仅限于在一个特定的地方。 这是我现在使用的连接字符串C#数据库连接SQL
string constring = "Data Source = (LocalDB)\\MSSQLLocalDB;
AttachDbFilename = C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf;
Integrated Security = True";
此连接字符串工作正常,所有,但上面说的,我想这是对环境的我把它
答
可以提供变量值,例如数据源,attachDbFilename等。然后在加载事件中检索值。或者使用配置文件来检索连接字符串。作为第一个解决方案出现这样
string constring = "Data Source = "+ YourDataSource +"; AttachDbFilename = "+ YourAttachedDBFilePath +"; Integrated Security = True";
答
你应该把数据库文件夹的应用程序(调试或发布)中,并用Application.StartupPath
答
如果可以调用它,然后把所需要的数据库到应用程序数据文件夹然后用在ConnectionString以下
Server=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|BarcodeDB.mdf;Database=BarcodeDB;
如果不是,那么做它使用提出百路达的选项,但在这种情况下,最好的办法,你必须知道电子在每个单一环境中的数据库的xact位置,或者在每个环境中进行搜索以找到必要的DB。
答
如果你想找到你的项目的路径,你可以使用:
string path = System.AppDomain.CurrentDomain.BaseDirectory;
的选择,如果你决定(旁边的可执行文件)存储在构建文件夹中的数据库文件:
string path = Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);
例子:
// filename of your Db file
string filename = "BarcodeDB.mdf";
// combine filename and your local path
string dbFilePath = Path.Combine(path, filename);
// use the db filepath in your constring using string interpolation
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = {dbFilePath}; Integrated Security = True";
所以,当你移动你的项目或有它在不同的机器(假设分贝文件存在),它应该能够找到它。
我如何检索加载时的值? –
您正在创建哪种类型的项目?根据项目类型不同而不同。大多数情况下,数据库连接字符串在Windows应用程序的app.config文件和Web应用程序的web.config文件中定义 –