1、MySQL-python
#Preconditions
sudo apt-get install python-dev libmysqlclient-dev # Ubuntu
sudo yum install python-devel mysql-devel # Red Hat / CentOS
#Installation
pip install MySQL-python
#!/ usr/bin/python
import MySQLdb
db = MySQLdb.connect(
host= "localhost" , #Hostname
user= "john" , #User name
passwd= "megajonhy" , #Password
db= "jonhydb" ) #Database name
#Before querying, you must first obtain the cursor
cur = db.cursor()
#All executed are native SQL statements
cur.execute( "SELECT * FROM YOUR_TABLE_NAME" )
for row in cur.fetchall():
print(row[ zero ])
db.close()
2、mysqlclient
#Windows installation
pip install some-package.whl
#Linux Prerequisites
sudo apt-get install python3-dev # debian / Ubuntu
sudo yum install python3-devel # Red Hat / CentOS
brew install mysql-connector-c # macOS (Homebrew)
pip install mysqlclient
3、PyMySQL
pip install PyMySQL
#To be compatible with mysqldb, just add
pymysql.install_as_MySQLdb()
import pymysql
conn = pymysql.connect(host= '127.0.0.1' , user= 'root' , passwd= "xxx" , db= 'mysql' )
cur = conn.cursor()
cur.execute( "SELECT Host,User FROM user" )
for r in cur:
print(r)
cur.close()
conn.close()
4、peewee
pip install peewee
import peewee
from peewee import *
db = MySQLDatabase( 'jonhydb' , user= 'john' , passwd= 'megajonhy' )
class Book (peewee.Model) :
author = peewee. CharField()
title = peewee. TextField()
class Meta :
database = db
Book.create_table()
book = Book(author= "me" , title= 'Peewee is cool' )
book.save()
for book in Book.filter(author= "me" ):
print(book.title)
5、SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_declarative import Address, Base, Person
class Address (Base) :
__tablename__ = 'address'
id = Column(Integer, primary_key= True )
street_name = Column(String( two hundred and fifty ))
engine = create_engine( ' sqlite:///sqlalchemy_example.db ' )
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
# Insert a Person in the person table
new_person = Person(name= 'new person' )
session.add(new_person)
session.commit()