如何使用Python将XML数据直接导入SQL Server?

时间:2019-02-06 15:48:50

标签: python sql-server xml

我有XML文件,我想使用Python将XML数据导入到SQL Server表中。我知道如果您要运行Python脚本,我们可以使用 sp_execute_external_script个存储过程。我还开发了将XML文件转换为CSV文件,然后使用批量插入将其加载到SQL Server的存储过程。但是可以直接加载而不转换为CSV文件吗?

我的XML转换为CSV并将CSV加载到SQL服务器代码如下:

CREATE PROCEDURE dbo.XMLParser
(
    @XMLFilePath VARCHAR(MAX),
    @CSVFilePath VARCHAR(MAX)
)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @a VARCHAR(MAX) = @XMLFilePath,
            @b VARCHAR(MAX) = @CSVFilePath;

    EXECUTE sp_execute_external_script @language = N'Python',
                                       @script = N'import xml.etree.ElementTree as ET
import csv

tree = ET.parse(a)
root = tree.getroot()

employee_data = open(b, "w")
csvwriter = csv.writer(employee_data)
employees_head = []

count = 0
for member in root.findall("Employee"):
    employee = []
    address_list = []
    if count == 0:
        name = member.find("Name").tag
        employees_head.append(name)
        PhoneNumber = member.find("PhoneNumber").tag
        employees_head.append(PhoneNumber)
        EmailAddress = member.find(''EmailAddress'').tag
        employees_head.append(EmailAddress)
        Address = member[3].tag
        employees_head.append(Address)
        csvwriter.writerow(employees_head)
        count = count + 1

    name = member.find("Name").text
    employee.append(name)
    PhoneNumber = member.find("PhoneNumber").text
    employee.append(PhoneNumber)
    EmailAddress = member.find("EmailAddress").text
    employee.append(EmailAddress)
    Address = member[3][0].text
    address_list.append(Address)
    City = member[3][1].text
    address_list.append(City)
    StateCode = member[3][2].text
    address_list.append(StateCode)
    PostalCode = member[3][3].text varcg
    address_list.append(PostalCode)
    employee.append(address_list)
    csvwriter.writerow(employee)
employee_data.close()',
                                       @params = N'@a varchar(max),@b varchar(max)',
                                       @a = @a,
                                       @b = @b;
    BULK INSERT dbo.Employee
    FROM 'E:\EmployeeData.csv'
    WITH
    (
        FIELDTERMINATOR = ',',
        ROWTERMINATOR = '\n'
    );
END;

1 个答案:

答案 0 :(得分:1)

您可以将XML转换为包含dics的python列表。您循环并在数据库中一行一行地插入。插入每一行时,您也可以“睡一秒钟”。