python3.6 sqlalchemy安装与使用

小白学习python,一边学一边做项目,直接从3.6开始

由于是做个比较简单的socket服务器,所以基本用python原生库,sql选用sqlalchemy

安装python就不说了(3.6自带pip)

 

1.先安装mysql模块

 

进入cmd,安装pymysql

 

"D:\Program Files\Python\Scripts\pip.exe" install pymysql

 

 

2.安装sqlalchemy

"D:\Program Files\Python\Scripts\pip.exe" install SQLAlchemy

 

3.在cmd里测试一下sqlalchemy安装成功没有

import sqlalchemy
sqlalchemy.__version__
'1.1.6'

只要打印出版本号,sqlalchemy安装成功

4.新建一个testAlchemy.py来测试一下

from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine

5.创建model.py文件 Column为字段

from sqlalchemy import Column, String

#创建模型
class User(sqlConfig.Base):
    __tablename__ = 'dev_user'
    uid = Column(String(20), primary_key=True)
    username = Column(String(20))
    realname = Column(String(20))
# 创建对象的基类:
Base = declarative_base()
# 初始化数据库连接:
engine = create_engine('mysql+pymysql://root:@localhost:3306/jfmonitor?charset=utf8') #现在是用pymysql做sql驱动了
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)
session = DBSession()
res = session.query(model.User).all()
for i in range(len(res)): 
    print("username:{0} realname:{1}".format(res[i].username, res[i].realname)

 

 

你可能感兴趣的:(python)