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


当前回答

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

其他回答

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

对于python 3.3

CyMySQL https://github.com/nakagami/CyMySQL

我在windows 7上安装了pip,只是 安装cymysql

(你不需要cython) 快速无痛

Mysqlclient是最好的,因为其他的只支持特定版本的python

 pip install mysqlclient

示例代码

    import mysql.connector
    import _mysql
    db=_mysql.connect("127.0.0.1","root","umer","sys")
    #db=_mysql.connect(host,user,password,db)
    # Example of how to insert new values:
    db.query("""INSERT INTO table1 VALUES ('01', 'myname')""")
    db.store_result()
    db.query("SELECT * FROM new1.table1 ;") 
    #new1 is scheme table1 is table mysql 
    res= db.store_result()
    for i in range(res.num_rows()):
        print(result.fetch_row())

参见https://github.com/PyMySQL/mysqlclient-python

对于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快得多

从python连接到MySQL的最佳方法是使用MySQL连接器/ python,因为它是MySQL的官方Oracle驱动程序,用于与python一起工作,并且它可以与python 3和python 2一起工作。

按照下面提到的步骤连接MySQL

使用PIP安装连接器 PIP安装mysql-connector-python

或者您可以从https://dev.mysql.com/downloads/connector/python/下载安装程序

使用mysql connector python的connect()方法连接mysql。将所需的参数传递给connect()方法。即主机、用户名、密码和数据库名。 从connect()方法返回的连接对象创建游标对象以执行SQL查询。 工作完成后关闭连接。

例子:

import mysql.connector
 from mysql.connector import Error
 try:
     conn = mysql.connector.connect(host='hostname',
                         database='db',
                         user='root',
                         password='passcode')
     if conn.is_connected():
       cursor = conn.cursor()
       cursor.execute("select database();")
       record = cursor.fetchall()
       print ("You're connected to - ", record)
 except Error as e :
    print ("Print your error msg", e)
 finally:
    #closing database connection.
    if(conn.is_connected()):
       cursor.close()
       conn.close()

参考资料- https://pynative.com/python-mysql-database-connection/

MySQL连接器Python的重要API

对于DML操作-使用cursor.execute()和cursor.executemany()来运行查询。在此之后,使用connection.commit()将您的更改保存到DB 获取数据—使用cursor.execute()运行查询,使用cursor.fetchall(), cursor.fetchone(), cursor.fetchmany(SIZE)获取数据