我已经从此处下载了最新的英文Wikipedia转储(enwiki- latest-pages-articles-multistream.xml),并且正在尝试将其导入SQL Server 2018。
我可以看到XML文件,因为它的重量超过75 GB,因此,在使用Bulk XML之前,我不知道应该创建哪种表。
我怎样才能做到这一点?我可以在 Python 或 C# 上编写一些脚本。提前致谢!
使用以下
SQL查询创建数据库
Create Database Feed ; GO USE [Feed] drop table Doc drop table Links ; GO CREATE TABLE [dbo].[Doc]( DocID int primary key, Title [varchar](50) NULL, URL [varchar](50) NULL, Abstract [varchar](50) NULL ) CREATE TABLE Links( DocID int, LinkType [varchar](10) NULL, Anchor [varchar](50) NULL, Link [varchar](50) NULL CONSTRAINT FK_DocID FOREIGN KEY (DocID) REFERENCES dbo.Doc (DocID) )
C#代码从xml填充数据库
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; using System.Data; using System.Data.SqlClient; namespace ConsoleApplication1 { class Program { const string FILENAME = @"c:\temp\test.xml"; const string CONNECTION_STRING = @"Server=.\SQLEXPRESS;Database=Feed;Trusted_Connection=True;"; const string INSERT_DOC = "INSERT INTO [Feed].[dbo].[Doc] (" + "DocID, Title , URL, Abstract)" + " VALUES " + "(@DocID, @Title, @URL, @Abstract)"; const string INSERT_LINK = "INSERT INTO [Feed].[dbo].[Links] (" + "DocID, LinkType , Anchor, Link)" + " VALUES " + "(@DocID, @Linktype, @Anchor, @Link)"; static void Main(string[] args) { SqlConnection conn = new SqlConnection(CONNECTION_STRING); conn.Open(); SqlCommand docCmd = new SqlCommand(INSERT_DOC, conn); docCmd.Parameters.Add("@DocID", SqlDbType.Int); docCmd.Parameters.Add("@Title", SqlDbType.VarChar, 50); docCmd.Parameters.Add("@URL", SqlDbType.VarChar, 50); docCmd.Parameters.Add("@Abstract", SqlDbType.VarChar, 50); SqlCommand linksCmd = new SqlCommand(INSERT_LINK, conn); linksCmd.Parameters.Add("@DocID", SqlDbType.Int); linksCmd.Parameters.Add("@LinkType", SqlDbType.VarChar, 10); linksCmd.Parameters.Add("@Anchor", SqlDbType.VarChar, 50); linksCmd.Parameters.Add("@Link", SqlDbType.VarChar, 50); XmlReader reader = XmlReader.Create(FILENAME); int id = 0; while (!reader.EOF) { if (reader.Name != "doc") { reader.ReadToFollowing("doc"); } if (!reader.EOF) { XElement doc = (XElement)XElement.ReadFrom(reader); id++; docCmd.Parameters["@DocID"].Value = id; docCmd.Parameters["@Title"].Value = (string)doc.Element("title"); docCmd.Parameters["@URL"].Value = (string)doc.Element("url"); docCmd.Parameters["@Abstract"].Value = (string)doc.Element("abstract"); int docRowsChanged = docCmd.ExecuteNonQuery(); foreach (XElement sublink in doc.Descendants("sublink")) { linksCmd.Parameters["@DocID"].Value = id; linksCmd.Parameters["@LinkType"].Value = (string)sublink.Attribute("linktype"); linksCmd.Parameters["@Anchor"].Value = (string)sublink.Element("anchor"); linksCmd.Parameters["@Link"].Value = (string)sublink.Element("link"); int linksRowsChanged = linksCmd.ExecuteNonQuery(); } } } } } }