繁体   English   中英

从xml插入数据库中的记录

[英]insert records in database from an xml

我正在写一个.net windows服务,我需要解析一个xml(有大约5000个节点)。 我需要解析这些节点并将数据(即5000行)插入到sql数据库中。 我应该用批量插入插入所有这些记录还是我要逐个插入它们? 有人可以帮我设计/算法以获得最佳性能吗?

使用C#asp.net导入XML数据到SQL Server表

DataSet reportData = new DataSet();
reportData.ReadXml(Server.MapPath(”report.xml”));

SqlConnection connection = new SqlConnection(”CONNECTION STRING”);
SqlBulkCopy sbc = new SqlBulkCopy(connection);
sbc.DestinationTableName = “report_table”;

//if your DB col names don’t match your XML element names 100%
//then relate the source XML elements (1st param) with the destination DB cols
sbc.ColumnMappings.Add(”campaign”, “campaign_id”);
sbc.ColumnMappings.Add(”cost”, “cost_USD”);

connection.Open();

//table 4 is the main table in this dataset
sbc.WriteToServer(reportData.Tables[4]);
connection.Close();

由于您已经在使用SQL Server,我建议您查看SSIS(Integration Services)。 它有一个内置的XML Source,可以直接进入SQL Server。 它很快,可以帮助您免于维护此代码。

为获得最佳性能,请使用仅向前XML阅读器事务批量插入器

当然,这个解决方案稍微复杂一点,很可能实现一个更简单的实现,需要更少的代码并且执行得非常好( EG.OPENXML

您可以使用XSLT转换将XML转换为带有insert语句的SQL文件。

在一天左右的时间里,我做过一次这样的概念验证。 这是我做的:

<xsl:strip-space elements="*"/>

<xsl:template match="auditlog">
<xsl:if test="sequence/struct/wstring[@value='edr']/../union/string/@value">
INSERT INTO AUDITLOGS (FILENAME, EVENTTIME, EDR) VALUES(
  '<xsl:value-of select="@filename"/>',
  '<xsl:value-of select="sequence/struct/union/any/sequence/struct/struct[@name='m_eventTime']/@datetime"/>',
  '<xsl:value-of select="sequence/struct/wstring[@value='edr']/../union/string/@value"/>'
);
<xsl:apply-templates select="sequence"/>
</xsl:if>
</xsl:template>

<xsl:template match="struct[@id='ModifiedBalance']">
INSERT INTO MODIFIEDBALANCE (SOURCEKIND, SOURCEID, TYPEID, NAMEID, ORIGINAL, CURRENT, LOGID)
SELECT
  '<xsl:value-of select="struct/enum/@value"/>',
  <xsl:value-of select="struct/longlong/@value"/>,
  <xsl:value-of select="struct/ushort[@id='BalanceTypeId']/@value"/>,
  <xsl:value-of select="struct/ushort[@id='BalanceNameId']/@value"/>,
  <xsl:value-of select="struct[@name='m_original']/@amount"/>,
  <xsl:value-of select="struct[@name='m_current']/@amount"/>,
  LOGID
FROM AUDITLOGS
  WHERE FILENAME = '<xsl:value-of select="../../../../../@filename"/>';
</xsl:template>

</xsl:stylesheet>

暂无
暂无

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

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