如何在运行时向数据集提供密码?

时间:2011-02-28 05:07:53

标签: passwords dataset connection-string

我有一个带密码的数据库。 如果我允许使用connectionstring保存密码,那么它将在.config文件中显示。

如何在运行时设置相同的内容?

检查:

Point ADO.Net DataSet to different databases at runtime?

Changing dataset connection string at runtime

但是需要一些方法来更改连接字符串以设置自身以避免在许多位置进行更改。

更新:这是Windows窗体应用程序。

3 个答案:

答案 0 :(得分:2)

这可以通过覆盖以下属性来实现。 步骤。

  1. 转到设置

  2. 点击查看代码

  3. 在视图代码中添加以下代码

  4. Vb,Net

    Default Public Overrides Property Item(ByVal propertyName As String) As Object
        Get
            If propertyName = "MyConnectionString" Then
                Return MyBase.Item(propertyName) & ";Password=Yourpassword;"
            End If
            Return MyBase.Item(propertyName)
        End Get
        Set(ByVal value As Object)
            MyBase.Item(propertyName) = value
        End Set
    End Property
    

    C#(使用代码转换器转换的粗略代码)

    public override object this[string propertyName] {
        get {
            if (propertyName == "MyConnectionString") {
                return base.Item(propertyName) + ";Password=Yourpassword;";
            }
            return base.Item(propertyName);
        }
        set { base.Item(propertyName) = value; }
    }
    

答案 1 :(得分:1)

使用DataSet,我使用以下代码:

myDataSet myData = new myDataSet();

myDataSetTableAdapters.myTableAdapter myInfo =
    new myDataSetTableAdapters.myTableAdapter();

myInfo.Connection.ConnectionString += ";Password=myPassword";
myInfo.Fill(myData.Info);

您可以自由设置tableAdapters ConnectionString的任何部分。

答案 2 :(得分:0)

功能性C#代码,刚刚测试过(基于@Sachin Chavan的精彩回答)。覆盖必须放在Settings.cs文件中:

public override object this[string propertyName]
{
    get
    {
        if (propertyName == "nameOfYourConnectionStringProperty")
        {
            return base[propertyName].ToString().Replace("******", "Y0uRpA$sW0rD");
        }
        return base[propertyName];
    }
    set { base[propertyName] = value; }
}