动态连接字符串数据库C# [英] Dynamic connection string database c#
问题描述
im始终使用以下代码行进行连接:
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";
其中txtmysource.Text / txtmyusername.Text / txtmypassword.Text / 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.
推荐答案
您可能想要 DbConnectionStringBuilder
,理想情况是您的RDBMS的正确选择-因此使用SQL Server:
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.
这篇关于动态连接字符串数据库C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!