python operation on mysql database

Original address: http://www.cnblogs.com/alex3714/articles/5978329.html

Install sqlalchemy

pip install SQLAlchemy<br><br>pip install pymysql #Since mysqldb still does not support py3, here we use pymysql to interact with sqlalchemy

  This is just the simplest sql table. If you add foreign key associations or something, the average programmer's brain capacity can't remember those sql statements, so with orm, the same function as above is realized. The code is as follows

import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
 
engine = create_engine("mysql+pymysql://root:alex3714@localhost/testdb",
                                    encoding='utf-8', echo=True)
 
 
Base = declarative_base() #Generate orm base class
 
class User(Base):
    __tablename__ = 'user' #表名
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    password = Column(String(64))
 
Base.metadata.create_all(engine) #Create table structure

  We have created the most basic table, so let's try to create a piece of data with orm

Session_class = sessionmaker(bind=engine) #Create a session session class with the database, note that what is returned to the session here is a class, not an instance
Session = Session_class() #Generate session instance
 
 
user_obj = User(name="alex",password="alex3714") #Generate the data object you want to create
print(user_obj.name, user_obj.id) #The object has not been created yet. If you don't believe me, print the id and find it is None.
 
Session.add(user_obj) #Add the data object to be created to this session, and it will be created uniformly in a while
print(user_obj.name, user_obj.id) #It is still not created at this time
 
Session.commit() #Only now is the unified submission and data creation

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324732052&siteId=291194637