簡體   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