Python -- use sqlalchemy to connect and operate MySQL database

(1) Link database

If SQLAlchemy is not installed, first use pip install sqlalchemy (if it shows no permissions, add sudo and try again)

from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

Base=declarative_base()
engine=create_engine("mysql+pymysql://username:password@host:port/dbname?charset=utf8",echo=True)
DBSession = sessionmaker(bind=engine)
session = DBSession()

   pymysql: Indicates the type of database link operation

   uesrname: the username of the database

   password: database password

   host: the host of the database

   dbname: the name of the database

The above has established a database connection, you can use the session to operate the database, add, delete, modify, check and so on.

(I did not create the entity class of the database here, but use SQL statements to operate on the database)

(2) Use SQL statements to operate the database

##Fixed SQL statement
query=session.execute('select * from student where id=44')
query=query.fetchall()//Get all the results fetchone() Get the first row of the results
print query
session.close()//Close the connection

##SQL statement with variables
query=session.execute('select * from student where id={0}.format(id)')
##Use {0} to represent the placeholder of the variable, format passes the variable in, and the value of the ID will replace the placeholder

##If there are multiple variables, pass multiple values ​​in format(id1,id2,id3), pay attention to pass the values ​​in order

 

 

 

 

 

Guess you like

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