C# 如何循环收集并保存到数据库
我在执行数据库时遇到了一些问题,通过循环我拥有的两个集合。请注意,这只是一个例子 第一个系列包括:性别-男性、女性 第二套包括:名字-约翰、詹姆斯、迈克、斯泰西、保拉 例如,我使用了for循环:C# 如何循环收集并保存到数据库,c#,C#,我在执行数据库时遇到了一些问题,通过循环我拥有的两个集合。请注意,这只是一个例子 第一个系列包括:性别-男性、女性 第二套包括:名字-约翰、詹姆斯、迈克、斯泰西、保拉 例如,我使用了for循环: for (int i = 0; i < genders.count; i++) { for (int j = 0, j < names.count; j++) { //call to stored procedure there //param
for (int i = 0; i < genders.count; i++)
{
for (int j = 0, j < names.count; j++)
{
//call to stored procedure there
//parameters
//execute
}
}
有没有人能提出不同的建议?我看不出有什么问题,但如果你问你的方法是否可以改进,是的 我会简单地使用一个包含性别属性的类
class Person
{
public bool IsFemale { get; set; }
public string Name { get; set; }
}
现在您可以创建单个集合,例如列表和循环
var persons = new List<Person>() {
new Person{IsFemale=false, Name="john"},new Person{IsFemale=false, Name="james"},
new Person{IsFemale=true, Name="stacy"},new Person{IsFemale=true, Name="paula"}
};
foreach(Person p in persons)
{
//call to stored procedure there
//parameters
//execute
}
首先,为什么不创建自己的类呢
class Person
{
private String name;
private String sex;
public Person(String name, String sex)
{
this.name = name;
this.sex = sex;
}
public String Name
{
get { return name; }
set { name = value; }
}
public String Sex
{
get { return sex; }
set { sex = value; }
}
}
然后创建一个人员列表
List<Person> people = new List<Person>();
people.add(new Person("Ashley", "Male"));
你的问题很模糊,但我会这么做…如何做?你想解决什么问题?什么问题?什么数据库?我想说,这是一种极为低效的与数据库交互的方式。最好创建一个查询并一次性将其发送到数据库,或者构建一组参数并将其发送到数据库。即使您不在SQL Server上,也是一本好书。@Oded我同意。一次数据库访问将是改进问题代码的最大单一方法。这就是我询问数据库的原因,我在sql server和oracle中都这样做过,尽管sql server更简单。另一个选择是确保有一个连接包装这些存储的过程调用,因为通常设置连接花费的时间最多,但没有那么好。但理想情况下……一次往返。
List<Person> people = new List<Person>();
people.add(new Person("Ashley", "Male"));
foreach(Person p in people)
{
Console.WriteLine(p.Name + " " + p.Sex);
}