Original address: http://www.cnblogs.com/alex3714/articles/5978329.html
Installing SQLAlchemy
Pip Install Sqlalchemy<br><br>pip install pymysql #由于mysqldb依然不支持py3, so here we use Pymysql to interact with SQLAlchemy
This is just the simplest SQL table, if you add a foreign key association or something, the general Programmer's brain capacity is not remember those SQL statements, so there is an ORM, to achieve the same function above, the code is as follows
Import sqlalchemyfrom sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import Declarative_basefrom SQLAlchemy import Column, Integer, String engine = Create_engine ("Mysql+pymysql://root:[email protected]/testdb", Encoding= ' Utf-8 ', echo=true) Base = Declarative_base () #生成orm基类 class User (base): __tablename__ = ' user ' #表名 id = column (Integer, primary_key=true) name = Column (string ()) Password = column (string (64)) Base.metadata.create_all (engine) #创建表结构
The most basic table we've created, so let's start with an ORM and try to create a piece of data.
Session_class = Sessionmaker (bind=engine) #创建与数据库的会话session class, notice that this is a class that is returned to the session, not the instance session = Session_ Class () #生成session实例 user_obj = User (name= "Alex", password= "alex3714") #生成你要创建的数据对象print (User_obj.name,user_ obj.id) #此时还没创建对象呢, do not believe you print the ID discovery or None session.add (user_obj) #把要创建的数据对象添加到这个session里, a unified create print (User_obj.name , user_obj.id) #此时也依然还没创建 session.commit () #现此才统一提交, creating data
Python's operations on MySQL database