1. 程式人生 > 實用技巧 >爬蟲-資料儲存(8)

爬蟲-資料儲存(8)

Python的orm資料儲存有三大型別:

pymysl,sqlachemy,peewee

安裝:

pipinstallpymysql【解決peewee的驅動依賴問題】

pip install peewee

peewee的具體實現如下:

from peewee import *

db = MySQLDatabase("spider", host="127.0.0.1", port=3306, user="root", password="root")


class Person(Model):
    name = CharField(max_length=20)
    birthday = DateField()

    
class Meta: database = db # This model uses the "people.db" database. table_name = "users"#修改表名字,一般預設為person。小寫的類名 #資料的增、刪、改、查 if __name__ == "__main__": db.create_tables([Person])   #這個列表傳入的引數將表示產生的表

peewee的增刪改查

from datetime import date

    #生成資料
    # uncle_bob = Person(name='Bob', birthday=date(1960, 1, 15))
# uncle_bob.save() # bob is now stored in the database # #查詢資料(只獲取一條) get方法在取不到資料會丟擲異常 # bobby = Person.select().where(Person.name == 'Bob').get() # print(bobby.birthday) # a = 1 # bobby = Person.get(Person.name == 'bobb') # print(bobby.birthday) #query是modelselect物件 可以當做list來操作 __getitem__
query = Person.select().where(Person.name == 'Bob') for person in query: person.delete_instance() # person.birthday = date(1960, 1, 17) # person.save() #在沒有資料存在的時候新增資料,存在的時候修改資料