python database programming: Python connection with several ways Detailed MySQL

Although many NoSQL database shine in recent years, but like a relational database such as MySQL is still one of the Internet's mainstream database, each school need to learn Python has a database, whether you are doing data analysis, or network reptile, Web developers, also, or machine learning, you can not do without going to interact with the database, and MySQL is the most popular database, this article describes several ways to operate Python MySQL, you can in the actual development process the reasonable choice according to the actual situation.

1、MySQL-python

MySQL-python called MySQLdb, Python is a drive to connect to MySQL's most popular, many frameworks are also based on this library development, unfortunately it only supports Python2.x, and when installed have a lot of pre-conditions, because it is C-based development of libraries in the Windows platform installation is very unfriendly, fails often, and now basically not recommended, it is substituted derivative version.

# 前置条件
sudo apt-get install python-dev libmysqlclient-dev # Ubuntu
sudo yum install python-devel mysql-devel # Red Hat / CentOS
# 安装
pip install MySQL-python

Windows exe files download directly through the installation, public No. reply "win" get the download link

#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect(
   host="localhost",  # 主机名
   user="john",     # 用户名
   passwd="megajonhy", # 密码
   db="jonhydb")    # 数据库名称
# 查询前,必须先获取游标
cur = db.cursor()
# 执行的都是原生SQL语句
cur.execute("SELECT * FROM YOUR_TABLE_NAME")
for row in cur.fetchall():
  print(row[0])
db.close()

2、mysqlclient

Because MySQL-python disrepair, and later appeared in its version Fork mysqlclient, fully compatible MySQLdb, while supporting Python3.x, is the Django ORM tool dependent, if you want to use native SQL database to operate, it is recommended that this drive. Installation and MySQLdb is the same, Windows can find the corresponding version of the package to download and install whl in https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient website.Here Insert Picture Description

# Windows安装
pip install some-package.whl
# linux 前置条件
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

We recommend learning Python buckle qun: 913066266, look at how seniors are learning! From basic web development python script to, reptiles, django, data mining, etc. [PDF, actual source code], zero-based projects to combat data are finishing. Given to every little python partner! Every day, Daniel explain the timing Python technology, to share some of the ways to learn and need to pay attention to small details, click on Join us on the p- ython learner gathering

3、PyMySQL

PyMySQL is pure Python implementation of the drive, can not compare MySQLdb speed, probably the biggest feature is its installation is not so complicated, but also compatible with MySQL-python

pip install PyMySQL
# 为了兼容mysqldb,只需要加入
pymysql.install_as_MySQLdb()

one example

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

Write native SQL process is very cumbersome, code duplication, not object-oriented thinking, which in turn gave birth to a lot of packages and package wrapper ORM framework, ORM is a mapping between Python object database relational tables, you no longer have a need to write SQL ORM statements. Improve the speed of writing code, compatible with a variety of database systems, such as sqlite, mysql, postgresql, the costs might be some losses in performance. If you are familiar with Django ORM comes, then peewee learning cost is almost zero. It is in Python is the most popular ORM framework.

pip install peewee

one example

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

If you are looking for both a native support for SQL, and support ORM tool, then SQLAlchemy is the best choice, it is very close to the Hibernate framework in Java

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(250))
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()

It is almost thoroughly understand the pros and cons of these types of database-driven, then you can choose one of them a systematic study then apply it to the project to go, I wish you a happy learning, I do not understand you can consult Kazakhstan.

to sum up

The above is connected with the Python MySQL posture several small series to introduce Hi, we want to help

Published 22 original articles · won praise 1 · views 30000 +

Guess you like

Origin blog.csdn.net/haoxun04/article/details/104237061