Python数据库(三)-使用sqlalchemy创建表 

首先需要安装sqlalchemy
根据所需情况调用数据库接口,对数据库进行操作
pymysql:
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
MySQL-Python:
mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
官方文档:http://docs.sqlalchemy.org/en/latest/dialects/index.html

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

__author__ = "MuT6 Sch01aR"

from sqlalchemy import create_engine

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy import Column,String,Integer

engine = create_engine("mysql+pymysql://root:root@127.0.0.1/test",encoding="utf-8",echo=True,max_overflow=5)

Base = declarative_base()

class User(Base):

    __tablename__ = "sql_test"

    id = Column(Integer,primary_key=True)

    user_name = Column(String(32))

    user_password = Column(String(64))

class Admin(Base):

    __tablename__ = "admin"

    id = Column(Integer, primary_key=True)

    username = Column(String(32))

    password = Column(String(64))

Base.metadata.create_all(engine)

运行

echo设置为True打印了返回的结果

在mysql中查看结果

表也创建成功

如果已经有了同名的表,将不会覆盖创建该表

给表插入数据

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

__author__ = "MuT6 Sch01aR"

from sqlalchemy import create_engine

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy import Column,String,Integer

from sqlalchemy.orm import sessionmaker

engine = create_engine("mysql+pymysql://root:root@127.0.0.1/test",encoding="utf-8",echo=False,max_overflow=5)

Base = declarative_base()

class Admin(Base):

    __tablename__ = "admin"

    id = Column(Integer, primary_key=True)

    username = Column(String(32))

    password = Column(String(64))

Base.metadata.create_all(engine)

Session_Class = sessionmaker(bind=engine)

Session = Session_Class()

t1 = Admin(username='test',password='123456')

t2 = Admin(username='test1',password='abcdef')

print(t1.username,t1.password)

print(t2.username,t2.password)

Session.add(t1)

Session.add(t2)

Session.commit()

运行结果

数据也创建成功