Chr*_*ang 19 c# sql sql-server connection-string
我正在尝试在C#中创建一个应该能够创建,备份和还原SQL Server数据库的程序.
为此,用户需要能够为所需的SQL Server(和数据库)设置连接字符串.
我想使用与Visual Studio相同的对话框来创建连接字符串.
这可能吗?
sta*_*ica 27
此答案中链接的数据连接对话框组件不再可供下载.
然而,一个(显然有点改变的)DataConnectionDialog
组件已经在NuGet上可用.
通过NuGet包管理器控制台将组件添加到Visual Studio项目:
Install-Package DataConnectionDialog
Run Code Online (Sandbox Code Playgroud)
// using Microsoft.Data.ConnectionUI;
// using System.Windows.Forms;
bool TryGetDataConnectionStringFromUser(out string outConnectionString)
{
using (var dialog = new DataConnectionDialog())
{
// If you want the user to select from any of the available data sources, do this:
DataSource.AddStandardDataSources(dialog);
// OR, if you want only certain data sources to be available
// (e.g. only SQL Server), do something like this instead:
dialog.DataSources.Add(DataSource.SqlDataSource);
dialog.DataSources.Add(DataSource.SqlFileDataSource);
…
// The way how you show the dialog is somewhat unorthodox; `dialog.ShowDialog()`
// would throw a `NotSupportedException`. Do it this way instead:
DialogResult userChoice = DataConnectionDialog.Show(dialog);
// Return the resulting connection string if a connection was selected:
if (userChoice == DialogResult.OK)
{
outConnectionString = dialog.ConnectionString;
return true;
}
else
{
outConnectionString = null;
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Dam*_*ith 23
注意:下面提到的对话框组件不再可供下载.除非您在过去检索过它,否则您可能无法获得此答案的示例代码.
替代方案:
DataConnectionDialog
NuGet现在有另外一种可用方式.有关详情,请参阅此答案.
MSDN Archive Gallery上的"数据连接对话框"(截至2015年9月1日)
数据连接对话框是随Visual Studio一起发布的数据库工具组件.它允许用户构建连接字符串并连接到特定的数据源.试试这个..
C#示例:
static void Main(string[] args)
{
DataConnectionDialog dcd = new DataConnectionDialog();
DataConnectionConfiguration dcs = new DataConnectionConfiguration(null);
dcs.LoadConfiguration(dcd);
if (DataConnectionDialog.Show(dcd) == DialogResult.OK)
{
// load tables
using (SqlConnection connection = new SqlConnection(dcd.ConnectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM sys.Tables", connection);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.HasRows);
}
}
}
}
dcs.SaveConfiguration(dcd);
}
Run Code Online (Sandbox Code Playgroud)
这里也提供源代码.我们可以根据许可证将源代码与我们的应用程序集成和重新分发.