如何使用python程序连接MySQL数据库?


当前回答

只是对上面的回答做了修改。 简单地运行这个命令来安装mysql for python

sudo yum install MySQL-python
sudo apt-get install MySQL-python

记住!区分大小写。

其他回答

SqlAlchemy


SQLAlchemy是Python SQL工具包和对象关系映射器 为应用程序开发人员提供了SQL的全部功能和灵活性。 SQLAlchemy提供了一个完整的著名企业级套件 持久性模式,为高效和高性能而设计 数据库访问,改编成简单的python域语言。

安装

pip install sqlalchemy

原始查询

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)

# insert into database
session.execute("insert into person values(2, 'random_name')")
session.flush()
session.commit()

蠕虫方式

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

Base = declarative_base()
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)

# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine

class Person(Base):
    __tablename__ = 'person'
    # Here we define columns for the table person
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

# insert into database
person_obj = Person(id=12, name="name")
session.add(person_obj)
session.flush()
session.commit()

MySQLdb是最直接的方法。您可以在连接上执行SQL查询。时期。

我更喜欢使用强大的SQLAlchemy,这也是python化的。下面是一个与查询相关的教程,下面是一个关于SQLALchemy的ORM功能的教程。

你可以用这种方式连接你的python代码到mysql。

import MySQLdb
db = MySQLdb.connect(host="localhost",
                 user="appuser",
                 passwd="",
                 db="onco")

cursor = db.cursor()

这里有一种方法,使用MySQLdb,它只支持Python 2:

#!/usr/bin/python
import MySQLdb

# Connect
db = MySQLdb.connect(host="localhost",
                     user="appuser",
                     passwd="",
                     db="onco")

cursor = db.cursor()

# Execute SQL select statement
cursor.execute("SELECT * FROM location")

# Commit your changes if writing
# In this case, we are only reading data
# db.commit()

# Get the number of rows in the resultset
numrows = cursor.rowcount

# Get and display one row at a time
for x in range(0, numrows):
    row = cursor.fetchone()
    print row[0], "-->", row[1]

# Close the connection
db.close()

参考这里

对于Python3.6,我找到了两个驱动程序:pymysql和mysqlclient。我测试了它们之间的性能,得到的结果是:mysqlclient更快。

下面是我的测试过程(需要安装python lib profilehooks来分析时间流逝:

select * from FOO;

立即在mysql终端执行: set中有46410行(0.10秒)

pymysql (2 . 4s):

from profilehooks import profile
import pymysql.cursors
import pymysql
connection = pymysql.connect(host='localhost', user='root', db='foo')
c = connection.cursor()

@profile(immediate=True)
def read_by_pymysql():
    c.execute("select * from FOO;")
    res = c.fetchall()

read_by_pymysql()

下面是pymysql的配置文件:

mysqlclient 0.4s)

from profilehooks import profile
import MySQLdb

connection = MySQLdb.connect(host='localhost', user='root', db='foo')
c = connection.cursor()

@profile(immediate=True)
def read_by_mysqlclient():
    c.execute("select * from FOO;")
    res = c.fetchall()

read_by_mysqlclient()

下面是mysqlclient的配置文件:

因此,mysqlclient似乎比pymysql快得多