python操作数据库有很多方法,下面介绍elixir来操作数据库。elixir是对sqlalchemy lib的一个封装,classes和tables是一一对应的,能够一步定义classes,tables和mappers,支持定义多个primary key。
定义model.py
from elixir import sqlalchemy
from elixir import *
engine =sqlalchemy.create_engine('mysql://root:root@localhost/') #the first root is the user, and the sencond root is the password
#engine.execute("DROP DATABASE IF EXISTS elixir")
engine.execute("CREATE DATABASE IF NOT EXISTS elixir")
metadata.bind='mysql://root:root@localhost:3306/elixir'
#metadata.bind.echo =True
class Movie(Entity):
using_options(tablename='movies')
title = Field(Unicode(30),primary_key = True)
year = Field(Integer, primary_key = True)
description = Field(UnicodeText)
director = ManyToOne('Director')
genres = ManyToMany('Genre')