且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过.NET WinForm应用程序连接到SQL Server

更新时间:2023-02-06 22:08:21

我会做这样的:

  • 使用一个 SqlConnectionStringBuilder 组件
  • 定义之类的服务器名,从数据库名称等您的app.config
  • 在该组件还具有两个属性的用户名和密码 - 填补这些从一个对话框,您提示用户输入这些信息
  • 在该SqlConnectionStringBuilder然后给你正确的连接字符串用于连接到SQL服务器
  • use a SqlConnectionStringBuilder component
  • define things like server name, database name etc. from your app.config
  • that component also has two properties for user name and password - fill those from a dialog box where you prompt the user for this information
  • that SqlConnectionStringBuilder then gives you the proper connection string to use for connecting to your SQL Server

更新:

我的建议是将存储这样的基本的连接字符串:

My suggestion would be to store the basic connection string like this:

<configuration>
  <connectionStrings>
     <add name="MyConnStr" 
          connectionString="server=A9;database=MyDB;" />
  </connectionStrings>
</configuration>

然后装入这个骨架连接字符串 - 到你的 SqlConnectionStringBuilder (这是不完整的,仅是行不通的!):

Then load this "skeleton" connection string (which is incomplete - that alone won't work!) into your SqlConnectionStringBuilder:

string myConnStr = ConfigurationManager.ConnectionStrings["MyConnStr"].ConnectionString;

SqlConnectionStringBuilder sqlcsb = new SqlConnectionStringBuilder(myConnStr);

然后抓住从用户的用户名和密码的对话框,然后将那些连接字符串生成器:

Then grab the user name and password from the user in a dialog box and add those to the connection string builder:

sqlcsb.UserID = tbxUserName.Text.Trim();
sqlcsb.Password = tbxPassword.Text.Trim();

,然后得到所产生的,完整的连接字符串中的 SqlConnectionStringBuilder

string completeConnStr = sqlcsb.ConnectionString;

using(SqlConnection _con = new SqlConnection(completeConnStr))
{
   // do whatever you need to do here....
}