Python interview one hundred questions - Data storage

table of Contents

  1. Read the XML node and attribute values
  2. Between XML documents and interchangeable dictionary
  3. Examples JSON string into the class
  4. Instance of the class is converted JSON string
  5. Operating SQLite database
  6. MySQL database operations
  7. ORM framework
  8. XML documents stored in the database MongoDB

01. reading XML node and attribute values

Here Insert Picture Description
Here Insert Picture Description

form xml.etree.ElementTree import parse

doc = parse('file/products.xml')
print(type(doc))
for item in doc.iterfimd('products/product'):   # 找product节点
    id = item.findtext('id')     # 找id节点里的文本
    name = item.findtext('name')
    price = item.findtext('price')
    uuid = item.get('uuid')     # 获得uuid属性值
    print('uuid','=', uuid)
    print('id', '=', id)
    print('name', '=', name)
    print('price', '=', price)
    print('-' * 9)

Here Insert Picture Description
to sum up
Here Insert Picture Description

Between 02.XML documents with interchangeable dictionary

Here Insert Picture Description

# 字典转xml
import dicttoxml
import os
from xml.dom.minidom import parseString

d = [20, 'name', {'name': 'Bill', 'age': 30, 'salary': 2000},
                 {'name': 'Mike', 'age': 40, 'salary': 3000},
                 {'name': 'John', 'age': 20, 'salary': 4000}]

bxml = dicttoxml.dicttoxml(d, custom_root='person')
xml = bxml.decode('utf-8')
dom = parseString(xml)
prettyxml = dom.toprettyxml(indent='  ')
f = open('persons.xml', 'w', encoding='utf-8')
f.write(prettyxml)
f.close()

# xml转字典
import xmltodict
import pprint

f = open('persons.xml', 'r', encoding='utf-8')
xml = f.read()
d = xmltodict.parse(xml)
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(d)
print(d)

Here Insert Picture Description
to sum up
Here Insert Picture Description

03. The JSON string into an instance of the class

Here Insert Picture Description

import json

class Product:
    def __init__(self, d):
        self.__dict__ = d

f = open('products.json', 'r')
jsonStr = f.read()
product = json.loads(jsonStr, object_hook=Product)   # 先用loads把type变为 'dict',再引入Product类
print(product.name)
print(product.price)

# 方法二:创建转换函数
def json2Product(d):
    return Product(d)

product1 = json.loads(jsonStr, object_hook=json2Product)    # json2Product不能加(),否则为调用
print(product1.name)
print(product1.price)

to sum up
Here Insert Picture Description

04. Examples of the class into a JSON string

Here Insert Picture Description

import json

class Product:
    def __init__(self, name, price, count):
        self.name = name
        self.price = price
        self.count = count

product = Product('特斯拉', 100000, 20)
def product2Dict(obj):
    return {
        'name':obj.name,
        'price':obj.price,
        'count':obj.count
    }
jsonStr = json.dumps(product, default=product2Dict, ensure_ascii=False)
print(jsonStr)
{"name": "特斯拉", "price": 100000, "count": 20}
jsonStr = json.dumps(product, default=product2Dict, ensure_ascii=True)	# 若改为True,则中文不会按原来输出
{"name": "\u7279\u65af\u62c9", "price": 100000, "count": 20}

# 问题二
f = open('products.json', 'r', encoding='utf-8')
jsonStr = f.read()


class Product:
    def __init__(self, d):
        self.__dict__ = d

products = json.loads(jsonStr, object_hook=Product)
for product in products:
    print(product.name)

jsonStr = json.dumps(products, default=product2Dict, ensure_ascii=False))
print(jsonStr)

to sum up
Here Insert Picture Description

05. Operating SQLite database

Published 21 original articles · won praise 5 · Views 1569

Guess you like

Origin blog.csdn.net/qq_36551226/article/details/104325521