[英]How to fill a SQL Server database in a C# winform
I'm writing a Winforms application in C# that stores data to Xml, then sends it via e-mail. 我正在用C#编写Winforms应用程序,该应用程序将数据存储到Xml,然后通过电子邮件发送。 These two things are running in their basic form. 这两件事以其基本形式运行。
But now I'm struggling with how to put this Xml file into a SQL Server database. 但是现在我在为如何将此Xml文件放入SQL Server数据库而苦苦挣扎。 I know that you can store value as Xml into SQL Server. 我知道您可以将值作为Xml存储到SQL Server中。 But is there a way that Xml data is stored as int
, varchar
etc.? 但是有没有一种方法可以将Xml数据存储为int
, varchar
等? Or in general a way how this is handled? 还是一般来说如何处理?
Thanks in advance! 提前致谢!
The following is the Xml - storing function: 以下是Xml-存储功能:
private void btnWriteCustomerToXml(object sender, EventArgs e)
{
Customer[] Kunden = new Customer[5];
Customer[0] = new Customer(1, "John", "A", 10000);
Customer[1] = new Customer(2, "John", "B", 20000);
Customer[2] = new Customer(3, "John", "C", 30000);
Customer[3] = new Customer(4, "John", "D", 40000);
Customer[4] = new Customer(5, "John", "E", 50000);
using (XmlWriter writer = XmlWriter.Create("TestMail.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("Employee");
foreach (Customer employee in Customer)
{
writer.WriteStartElement("Employee");
writer.WriteElementString("ID", employee.Id.ToString());
writer.WriteElementString("Vorname", employee.FirstName);
writer.WriteElementString("Nachname", employee.LastName);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
string output = "XML file was successfully created!";
MessageBox.Show(output);
}
}
You can use the native XQuery support in SQL Server to "shred" your XML into relational data and store it - something like this: 您可以使用SQL Server中的本机XQuery支持将XML“切碎”成关系数据并存储它-像这样:
-- declare input - could be the input parameter of a stored procedure or something
DECLARE @input XML = '<Employees><Employee><ID>4040</ID><Vorname>Dieter</Vorname><Nachname>Mueller</Nachname></Employee></Employees>'
-- INSERT INTO your table
INSERT INTO dbo.Employee(ID, Vorname, Nachname)
-- shred the incoming XML into rows of data, based on the XPath /Employees/Employee
SELECT
XEmp.value('(ID)[1]', 'int'),
XEmp.value('(Vorname)[1]', 'varchar(50)'),
XEmp.value('(Nachname)[1]', 'varchar(50)')
FROM
@input.nodes('/Employees/Employee') AS XTbl(XEmp)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.