Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic connection string database c#

Tags:

c#

database

im always use this line of code for connection :

 string ConnectString = "datasource = mysource; username = myusername; password = mypassword; database = mydatabasename";

What im trying to do thistime is instead of writing each time my server data in script directly i want to fill some textbox . so im try to do something like this

string ConnectString = "datasource = txtmysource.Text; username = txtmyusername.Text; password = txtmypassword.Text; database = txtmydatabasename.Text";

where txtmysource.Text / txtmyusername.Text / txtmypassword.Text / txtmydatabasename.Text are the names of textbox in UI. but i can't find the write way to do it.

like image 730
Raouf Bessghaier Avatar asked Dec 12 '19 12:12

Raouf Bessghaier


2 Answers

You probably want DbConnectionStringBuilder, ideally the correct one for your RDBMS - so with SQL Server:

var builder = new SqlConnectionStringBuilder
{
    UserID = txtmyusername.Text,
    DataSource = txtmysource.Text,
    Password = txtmypassword.Text,
    InitialCatalog = txtmydatabasename.Text,
};
var connectString = builder.ConnectionString;

The crucial bit here is that it will apply the correct character escaping etc if (for example) any of the elements contain reserved / non-trivial characters such as whitespace, commas, quotes, etc.

like image 157
Marc Gravell Avatar answered Sep 19 '22 17:09

Marc Gravell


Maybe with interpolate string like this :

string ConnectString = $"datasource = {txtmysource.Text}; username = {txtmyusername.Text}; password = {txtmypassword.Text}; database = {txtmydatabasename.Text}";
like image 45
Francois Borgies Avatar answered Sep 20 '22 17:09

Francois Borgies