[英]How can insert data to database from arraylist in C#
I have a class as 'Student'.我有一个 class 作为“学生”。 I have done xml parse and then i recorded xml elements to arraylist using this class.Then i want to insert the elements from arraylist to database.How can i do this?
I have done xml parse and then i recorded xml elements to arraylist using this class.Then i want to insert the elements from arraylist to database.How can i do this?
int id=1;
Arraylist arylist=new Arraylist();
xmlparse.Load(Url);
XmlNodeList nodes = xmlparse.SelectNodes("...");//Url nodes
foreach (XmlNode item in nodes)
{
XmlNode innode = item.SelectSingleNode("name");
string xml_name = innode != null ? innode.InnerText : "";
innode = item.SelectSingleNode("parts");
string xml_parts = innode != null ? innode.InnerText : "";
... ...
arylist.Add(new Student(id, xml_name, xml_parts...));
id++;
}
I tried to something like this.But i couldnt do exactly.Is there anyone can u help me我试过这样的事情。但我不能完全做到。有没有人可以帮助我
foreach (int i in arylist)
{
var mycommand = new OleDbCommand("insert into Student (name,parts) values (@name,@parts)", connection);
mycommand.Parameters.AddWithValue("@name",i dont know what i should write here);
}
Your code will need to look like:您的代码需要如下所示:
using(mycommand = new OleDbCommand("insert into Student (name,parts) values (@name,@parts)", connection)){
mycommand.Parameters.AddWithValue("@name","dummy name");
mycommand.Parameters.AddWithValue("@parts","dummy part"); //assuming parts is a string - you haven't made any code to parse it
foreach (object o in arylist)
{
Student s = (Student)o; //this isn't needed if you use a List<Student>..
mycommand.Parameters["@name"].Value = s.Name; //or whatever your name property is
mycommand.Parameters["@parts"].Value = s.Parts; //or whatever your parts property is
mycommand.ExecuteNonQuery();
}
}
We have all our students in an ArrayList (not the best choice; but everyone is stuck on telling you about that so I won't repeat their words) so we should:我们所有的学生都在 ArrayList 中(不是最好的选择;但每个人都坚持告诉你,所以我不会重复他们的话)所以我们应该:
Open()
ed it elsewhere).Open()
在别处编辑它)。 We do this in a using block so c# will clean up after us - always good to do with DB stuff.Take a read of this, to guide your future coding: https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/阅读此内容,以指导您未来的编码: https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
I don't personally take much issue with AddWithValue if it's used for parameters that are not in a WHERE clause but you should at least appreciate what it's doing and the trouble it can cause如果 AddWithValue 用于不在 WHERE 子句中的参数,我个人不会有太多问题,但您至少应该了解它在做什么以及它可能导致的麻烦
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.