Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connecting to sql server through a .net winform application

i am making a simple c#.net winform application with a form1, which will connect to sql server.

i want that before establishing a connection to sql server , the application asks the user to enter the login name & password to connect.

for this what should i do:

take the login name & password in two text boxes & pass them the to the connection string or should i pass them to the app.config file & then use the string from app.config file in the form1.cs?

will this be ok with the security issues? if not, then what are the other ways of implementing this task?

like image 316
sqlchild Avatar asked Jun 21 '26 12:06

sqlchild


1 Answers

I would do this:

  • 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

Update:

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

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

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();

and then get the resulting, complete connection string from the SqlConnectionStringBuilder:

string completeConnStr = sqlcsb.ConnectionString;

using(SqlConnection _con = new SqlConnection(completeConnStr))
{
   // do whatever you need to do here....
}
like image 72
marc_s Avatar answered Jun 23 '26 02:06

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!