我使用通过C#创建的WinForm表单连接到Sql server数据库。
要连接数据库,用户必须提供登录名和密码。
我使用配置文件App.config来存储connectionString,如下所示:
<ConnectionStrings>
<Add name = "K1" connectionString = "Data Source = HP; Initial Catalog = TRVANALYT; User ID = {0}; Password = {1}
ProviderName = "System.Data.SqlClient" />
</ ConnectionStrings>
向我提出的问题不会保存新的connectionString
刷新connextionString K1我必须重建程序,它会给出正确的结果
如果你有建议
什么是最佳做法?
非常感谢你
我的代码:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string connexionstring = ConfigurationManager.ConnectionStrings["K1"].ToString();
var connectionStringsSection = (ConnectionStringsSection) config.GetSection("connectionStrings");
string NewConnexionstring = string.Format(connexionstring, txtUser.Text, txtPwd.Text);
connectionStringsSection.ConnectionStrings["K1"].ConnectionString = NewConnexionstring; //Set new connectionString with user and password
connectionStringsSection.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
ConfigurationManager.RefreshSection("connectionStrings");
的App.config
<configSections>
</configSections>
<connectionStrings>
<add name="K1" connectionString="Data Source=HP;Initial Catalog=TRVANALYT;User ID={0};Password={1}" providerName="System.Data.SqlClient" />
</connectionStrings>
答案 0 :(得分:0)
我有同样的问题,但是当我调试时,我意识到ConnectionString已保存,但是当我创建一个新对象时,这个的Connectionstring为false。 我是通过这种方式解决的:
代码
public partial class QuanLySieuThiEntities : DbContext
{
//This is the default constructor
public QuanLySieuThiEntities()
: base("name=QuanLySieuThiEntities")
{
}
//Add this constructor
public QuanLySieuThiEntities(String connString)
: base(connString)
{
}
}
代码
string _conString = System.Configuration.ConfigurationManager.ConnectionStrings["QuanLySieuThiEntities"].ConnectionString;
QuanLySieuThiEntities newObject = new QuanLySieuThiEntities(_conString);