通过sqlalchemy操作mysql

# 安装 pip3 install sqlalchemy

import sqlalchemy

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,INTEGER,String
from sqlalchemy.orm import sessionmaker # 创建连接
engine = create_engine("mysql+pymysql://root:abc123@localhost/testdb",encoding="utf-8",echo=True) # 生成ORM基类
Base = declarative_base() class User(Base):
__tablename__ = 'user'
id = Column(INTEGER,primary_key=True)
name = Column(String(32))
password = Column(String(64)) Base.metadata.create_all(engine) # 创建表结构 Session_class = sessionmaker(bind=engine) # 创建与数据库连接会话的类
Session = Session_class() # 生成session实例 #cursor user_obj = User(name="dennis",password="abc123") #生成要创建的数据对象
user_obj2 = User(name="alex",password="abcd")
print(user_obj.name,user_obj.id)
Session.add(user_obj)
Session.add(user_obj2) Session.commit()
上一篇:[百度空间] [转]DLL地狱及其解决方案


下一篇:Hbase1.2.3安装