简体   繁体   English

使用 c# Windows 窗体在 xml 文件中读取/写入数据库连接字符串

[英]Read/write Database Connection string in xml file using c# Windows Form

I am developing an c# application in which I need to fetch data from oracle database server.我正在开发一个 c# 应用程序,我需要在其中从 oracle 数据库服务器获取数据。 In my application I do not want to make a hard coded connection string because sometimes we have to connect it with different DB (for testing purpose it has same schema).在我的应用程序中,我不想制作硬编码的连接字符串,因为有时我们必须将它连接到不同的数据库(出于测试目的,它具有相同的架构)。

For this I have a plan that I create an xml file and a new form(with admin rights) using this form I update/insert database credentials in xml file or use app.config , but the problem is i don't have any idea how to read and write xml file in predefined manner (in same manner as a connection string should be).为此,我有一个计划,我使用此表单创建一个xml文件和一个新表单(具有管理员权限)我在 xml 文件中更新/插入数据库凭据或使用app.config ,但问题是我不知道如何以预定义的方式读取和写入 xml 文件(与连接字符串的方式相同)。

Can you please help me out for creating new xml file or have any batter idea?你能帮我创建新的 xml 文件或有任何更好的想法吗?

how about this code?这段代码怎么样?

public static string ClientName, DbType, ConnectionString;
        static DB()
        {
            try
            {
                DataTable Dt = new DataTable("Settings");
                DataColumn Client = new DataColumn("Client", typeof(string));
                DataColumn DataBaseType = new DataColumn("DataBaseType", typeof(string));

                DataColumn ConString = new DataColumn("ConnectionString", typeof(string));
                Dt.Columns.Add(Client);
                Dt.Columns.Add(DataBaseType);
                Dt.Columns.Add(ConString);
                Dt.ReadXml(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Settings.xml");
                DB.ClientName = Dt.Rows[0]["Client"].ToString();
                DB.DbType = Dt.Rows[0]["DataBaseType"].ToString();
                DB.Port = Dt.Rows[0]["Port"].ToString();
                DB.ConnectionString = Dt.Rows[0]["ConnectionString"].ToString();
            }
            catch(Exception ex)
             {
            // Exception message
             }

and xml file code is和xml文件代码是

<?xml version="1.0" standalone="yes"?>
<DocumentElement>
    <Settings>
        <Client>DSCL</Client>
        <DataBaseType>ORACLE</DataBaseType>

            <ConnectionString>providerName=system.data.oracleclient;User ID=****;password=****;Data Source=*****;Persist Security Info=True;Provider=OraOLEDB.Oracle;</ConnectionString>

  </Settings>
</DocumentElement>

Create that class创建那个类

[Serializable()]
public class Car
{
    [System.Xml.Serialization.XmlElement("StockNumber")]
    public string StockNumber { get; set; }

    [System.Xml.Serialization.XmlElement("Make")]
    public string Make { get; set; }

    [System.Xml.Serialization.XmlElement("Model")]
    public string Model { get; set; }
}


[Serializable()]
[System.Xml.Serialization.XmlRoot("CarCollection")]
public class CarCollection
{
    [XmlArray("Cars")]
    [XmlArrayItem("Car", typeof(Car))]
    public Car[] Car { get; set; }
}

The Deserialize function:反序列化功能:

CarCollection cars = null;
string path = "cars.xml";

XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));

StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();

And the slightly tweaked xml (I needed to add a new element to wrap ...Net is picky about deserializing arrays):和稍微调整的 xml (我需要添加一个新元素来包装 ...Net 对反序列化数组很挑剔):

<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>

Also take a look at也看看

Loading custom configuration files 加载自定义配置文件

http://www.codeproject.com/Articles/32490/Custom-Configuration-Sections-for-Lazy-Coders http://www.codeproject.com/Articles/32490/Custom-Configuration-Sections-for-Lazy-Coders

App.Config:应用程序配置:

<configuration>     
  <connectionStrings>
    <add name="connstring1"
        connectionString="DataSource=123.123.123.123;UserID=XXX;Password=XXX;" />
  </connectionStrings>     
</configuration>

C# code: C#代码:

var appConfig = ConfigurationManager.OpenExeConfiguration("your.exe");
string connectionstring = appConfig.ConnectionStrings.ConnectionStrings["connstring1"].ConnectionString;

use the app config for your connectionStrings:为您的 connectionStrings 使用应用程序配置:

<?xml version="1.0" encoding="utf-8" ?>
 <configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
 <connectionStrings>
    <add name="MyDatabase" connectionString="......"/>
 </connectionStrings>
</configuration>

add a reference to System.Configuration in your application and get the connection string via :在您的应用程序中添加对System.Configuration的引用并通过以下方式获取连接字符串:

string connectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;

You are trying to reinvent a wheel.您正在尝试重新发明轮子。

As people mentioned here, .config files are meant for application configuration.正如人们在这里提到的,.config 文件用于应用程序配置。 There is a dedicated section for connection strings in them, so you're advised to use it as it is standard and convenient.其中有一个专门的连接字符串部分,因此建议您使用它,因为它是标准且方便的。

Here is your config:这是你的配置:

<configuration>
....
<connectionStrings>
    <add name="OracleConnectionString" connectionString="providerName=system.data.oracleclient;User ID=****;password=****;Data Source=*****;Persist Security Info=True;Provider=OraOLEDB.Oracle;" providerName="System.Data.OracleClient" />
</connectionStrings>
</configuration>

and here is the code snippet to modify it:这是修改它的代码片段:

string user = "Me";
string pwd = "qwerty";

Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringsSection section = (ConnectionStringsSection)cfg.GetSection("connectionStrings");

var currentConnectionString = section.ConnectionStrings["OracleConnectionString"];
currentConnectionString.ConnectionString = string.Format("providerName=system.data.oracleclient;User ID={0};password={1};Data Source=*****;Persist Security Info=True;Provider=OraOLEDB.Oracle;", user, pwd);

cfg.Save();
ConfigurationManager.RefreshSection("connectionStrings");

Notes: 1. Be aware that you are saving .config in the /bin, not in your project folder, so when you rerun/redeploy your application, the changes will be discarded.注意: 1. 请注意,您将 .config 保存在 /bin 中,而不是项目文件夹中,因此当您重新运行/重新部署应用程序时,更改将被丢弃。 2. When debugging you won't see the changes as VS creates HOST process and copies a fresh .config file to the /bin. 2. 调试时您不会看到更改,因为 VS 创建 HOST 进程并将新的 .config 文件复制到 /bin。 To see the changes you should run without debugging.要查看您应该在没有调试的情况下运行的更改。 Cheers.干杯。

Create a datatable with your values.使用您的值创建数据表。 do Dt.WriteXml(fileName);做 Dt.WriteXml(fileName); It will generate xml file.它将生成 xml 文件。 maintain this xml in future.将来维护这个 xml。 use Dt.ReadXml(filename) to get the values back in application.使用 Dt.ReadXml(filename) 将值返回到应用程序中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM