[英]Best method to store a large number of constants C#
Fairly new to c#, I have a datatable with 250 rows, one of the columns will be populated with constant values (these values are strings). 对C#来说,这是很新的知识,我有一个包含250行的数据表,其中一列将填充常量值(这些值是字符串)。 What is the best way to store these constants? 存储这些常数的最佳方法是什么? Any reference links to your suggestions would be greatly appreciated. 任何参考链接到您的建议将不胜感激。 One method I was thinking was using an xml file but I am unsure how easy it would then be to add values to the datatable. 我当时想到的一种方法是使用xml文件,但是我不确定向数据表中添加值会多么容易。
Assuming that you want to store from a file to a database... 假设您要从文件存储到数据库中...
C# XML support is fine : C#XML支持很好:
using System;
using System.Xml;
Then assuming you have this kind of XML structure : 然后假设您具有这种XML结构:
<Db>
<Item str_attr="ghjgjg" other_attr="0" .../>
<Item str_attr="fsfsff" other_attr="1" .../>
...
</Db>
Then you can browse it as follows : 然后,您可以如下浏览它:
XmlTextReader textReader = new XmlTextReader("db.xml");
while (textReader.Read())
{
String str = textReader.GetAttribute("str_attr");
if (str != null) { // The current item has an attribute named "str_attr"
// Code to insert 'str' to db here
}
}
This is pretty straight forward. 这很简单。
Possible code to populate the database : 可能的代码来填充数据库:
SqlCommand cmd = new SqlCommand(...);
cmd.CommandText = "INSERT INTO my_table (my_str_field) " + "VALUES (@str)";
cmd.Parameters.AddWithValue("@str", str);
cmd.ExecuteNonQuery();
So what I ended up doing is the following: 因此,我最终要做的事情如下:
I Created an xml with the following format 我用以下格式创建了一个xml
<Db>
<identify>
<row>
<column2>Name</column2>
<column3></column3>
</row>
:
:
:
</identify>
</Db>
Then to read the information from the xml file I used the following code: 然后从xml文件读取信息,我使用了以下代码:
XmlTextReader textReader = new XmlTextReader("db.xml");
textReader.ReadStartElement("Db");
string column2="";
for (int row = 0; row < NumOfRows; row++)
{
if (row == 0)
{
textReader.ReadStartElement("identify");
}
textReader.ReadStartElement("row");
column2 = textReader.ReadElementString("column2");
dataView[row][2] = column2;
dataView[row][3] = textReader.ReadElementString("column3");
textReader.ReadEndElement(); //row
}
Note: I am using the information stored in the xml and placing it into a datatable. 注意:我正在使用存储在xml中的信息并将其放入数据表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.