首先需要安装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
# -*- coding:utf-8 -*-
__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)
#连接mysql数据库,echo为是否打印结果
Base = declarative_base() #生成orm基类
class User(Base): #继承生成的orm基类
__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) #创建表结构
#父类Base调用所有继承他的子类来创建表结构
运行
echo设置为True打印了返回的结果
在mysql中查看结果
表也创建成功
如果已经有了同名的表,将不会覆盖创建该表
给表插入数据
# -*- coding:utf-8 -*- __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_Class为一个类 Session = Session_Class() #实例化与数据库的会话 t1 = Admin(username=‘test‘,password=‘123456‘) #生成admin表要插入的一条数据 t2 = Admin(username=‘test1‘,password=‘abcdef‘) #生成admin表要插入的一条数据 print(t1.username,t1.password) print(t2.username,t2.password) Session.add(t1) #把admin表要插入的数据添加到Session里 Session.add(t2) Session.commit() #提交,不然不能创建数据
运行结果
数据也创建成功