首页 文章

如何使用Python连接MySQL数据库?

提问于
浏览
1005

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

21 回答

  • 1160

    要在Python中编写数据库应用程序,需要遵循以下五个步骤:

    使用以下命令导入SQL接口:

    >>> import MySQLdb
    

    使用以下命令与数据库 Build 连接:

    conn = MySQLdb.connect(host ='localhost',user ='root',passwd ='')...其中host是主机的名称,后跟用户名和密码 . 如果是root,则无需提供密码 .

    使用以下命令为连接创建游标:

    >>>cursor = conn.cursor()
    

    使用此游标执行任何SQL查询,如下所示 - 此处的输出显示受此查询影响的行数:

    cursor.execute('创建数据库库')//表示受影响的行数

    >>> cursor.execute('use Library')
    
    >>>table='create table books(book_accno char(30) primary key, book_name
    char(50),no_of_copies int(5),price int(5))'
    >>> cursor.execute(table)
    

    最后,获取结果集并迭代此结果集 . 在此步骤中,用户可以获取结果集,如下所示:

    >>> cursor.execute('select * from books')
    >>> cursor.fetchall()
    

    (('Py9098','用Python编程',100L,50L),('Py9099','用Python编程',100L,50L))

  • 165

    First install the driver (Ubuntu)

    • sudo apt-get install python-pip

    • sudo pip install -U pip

    • sudo apt-get install python-dev libmysqlclient-dev

    • sudo apt-get install MySQL-python

    MySQL database connection codes

    import MySQLdb
    conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "pass",db = "dbname")
    cursor = conn.cursor ()
    cursor.execute ("SELECT VERSION()")
    row = cursor.fetchone ()
    print "server version:", row[0]
    cursor.close ()
    conn.close ()
    
  • 11

    作为db驱动程序,还有oursql . 在该链接上列出的一些原因,说明为什么我们的更好:

    oursql具有真正的参数化,完全将SQL和数据完全发送到MySQL . oursql允许将文本或二进制数据流式传输到数据库并从数据库流出,而不是要求在客户端中缓存所有内容 . oursql可以懒惰地插入行并且懒惰地获取行 . oursql默认支持unicode . oursql支持python 2.4到2.7,2.6上没有任何弃用警告(参见PEP 218),而2.7没有完全失败(参见PEP 328) . oursql在python 3.x上本机运行 .

    那么如何使用oursql连接mysql?

    与mysqldb非常相似:

    import oursql
    
    db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name')
    cur=db_connection.cursor()
    cur.execute("SELECT * FROM `tbl_name`")
    for row in cur.fetchall():
        print row[0]
    

    tutorial in the documentation非常体面 .

    当然,对于ORM,SQLAlchemy是一个不错的选择,正如其他答案中已经提到的那样 .

  • 17

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

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

    原始sql: select * from FOO;

    立即在mysql终端执行: 46410 rows in set (0.10 sec)

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

  • 1

    如果你想避免安装mysql头只是为了从python访问mysql,请停止使用MySQLDb .

    使用pymysql . 它完成了MySQLDb的所有工作,但它完全是用 NO External Dependencies 在Python中实现的 . 这使得所有操作系统上的安装过程一致且容易 . pymysql 是MySQLDb和IMHO的替代品,没有理由将MySQLDb用于任何事情......真的! - PTSD from installing MySQLDb on Mac OSX and *Nix systems ,但那只是我 .

    Installation

    pip install pymysql

    就是这样......你准备好了 .

    Example usage from pymysql Github repo

    import pymysql.cursors
    import pymysql
    
    # Connect to the database
    connection = pymysql.connect(host='localhost',
                                 user='user',
                                 password='passwd',
                                 db='db',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
    
    try:
        with connection.cursor() as cursor:
            # Create a new record
            sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
            cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
    
        # connection is not autocommit by default. So you must commit to save
        # your changes.
        connection.commit()
    
        with connection.cursor() as cursor:
            # Read a single record
            sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
            cursor.execute(sql, ('webmaster@python.org',))
            result = cursor.fetchone()
            print(result)
    finally:
        connection.close()
    

    另外 - 快速透明地替换现有代码中的MySQLdb

    如果你有使用MySQLdb的现有代码,你可以使用这个简单的过程轻松地用pymysql替换它:

    # import MySQLdb << Remove this line and replace with:
    import pymysql
    pymysql.install_as_MySQLdb()
    

    对MySQLdb的所有后续引用都将透明地使用pymysql .

  • 2

    尝试使用MySQLdb

    这里有一个页面:http://www.kitebird.com/articles/pydbapi.html


    从页面:

    # server_version.py - retrieve and display database server version
    
    import MySQLdb
    
    conn = MySQLdb.connect (host = "localhost",
                            user = "testuser",
                            passwd = "testpass",
                            db = "test")
    cursor = conn.cursor ()
    cursor.execute ("SELECT VERSION()")
    row = cursor.fetchone ()
    print "server version:", row[0]
    cursor.close ()
    conn.close ()
    
  • 6

    MySQLdb是直截了当的方式 . 您可以通过连接执行SQL查询 . 期 .

    我喜欢的方式也是pythonic,而是使用强大的SQLAlchemy . 这是一个query related教程,这是SQLALchemy的ORM capabilities教程 .

  • 0

    首先,从https://dev.mysql.com/downloads/connector/python/安装python-mysql连接器

    在Python控制台上输入:

    pip install mysql-connector-python-rf
    import mysql.connector
    
  • 111

    另外看看Storm . 它是一个简单的SQL映射工具,允许您轻松编辑和创建SQL条目,而无需编写查询 .

    这是一个简单的例子:

    from storm.locals import *
    
    # User will be the mapped object; you have to create the table before mapping it
    class User(object):
            __storm_table__ = "user" # table name
            ID = Int(primary=True) #field ID
            name= Unicode() # field name
    
    database = create_database("mysql://root:password@localhost:3306/databaseName")
    store = Store(database)
    
    user = User()
    user.name = u"Mark"
    
    print str(user.ID) # None
    
    store.add(user)  
    store.flush() # ID is AUTO_INCREMENT
    
    print str(user.ID) # 1 (ID)
    
    store.commit() # commit all changes to the database
    

    查找和反对使用:

    michael = store.find(User, User.name == u"Michael").one()
    print str(user.ID) # 10
    

    使用主键查找:

    print store.get(User, 1).name #Mark
    

    有关详细信息,请参阅tutorial .

  • 3

    只是对上述答案的修改 . 只需运行此命令即可为python安装mysql

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

    记得!它区分大小写 .

  • 8

    尽管有上述所有答案,但如果您不想提前连接到特定数据库,例如,如果要创建数据库仍为(!),则可以使用 connection.select_db(database) ,如下所示 .

    import pymysql.cursors
    connection = pymysql.connect(host='localhost',
                             user='mahdi',
                             password='mahdi',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)
    cursor = connection.cursor()
    cursor.execute("CREATE DATABASE IF NOT EXISTS "+database)
    connection.select_db(database)
    sql_create = "CREATE TABLE IF NOT EXISTS "+tablename+(timestamp DATETIME NOT NULL PRIMARY KEY)"
    cursor.execute(sql_create)
    connection.commit()
    cursor.close()
    
  • 98

    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

  • -1

    使用Python以3个步骤连接到MYSQL

    1 - Setting

    您必须在执行任何操作之前安装MySQL驱动程序 . 与PHP不同,默认情况下只使用Python安装SQLite驱动程序 . 该最常用的包是MySQLdb但是使用easy_install很难安装它 .

    对于Windows用户,您可以获得exe of MySQLdb .

    对于Linux,这是一个休闲包(python-mysqldb) . (您可以在命令行中使用 sudo apt-get install python-mysqldb (基于debian的发行版), yum install MySQL-python (基于rpm)或 dnf install python-mysql (适用于现代fedora发行版) . )

    对于Mac,你可以install MySQLdb using Macport .

    2 - Usage

    安装完成后,重启 . 这不是强制性的,但如果出现问题,它将阻止我在这篇文章中回答3或4个其他问题 . 所以请重新启动 .

    然后它就像使用任何其他包:

    #!/usr/bin/python
    import MySQLdb
    
    db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                         user="john",         # your username
                         passwd="megajonhy",  # your password
                         db="jonhydb")        # name of the data base
    
    # you must create a Cursor object. It will let
    #  you execute all the queries you need
    cur = db.cursor()
    
    # Use all the SQL you like
    cur.execute("SELECT * FROM YOUR_TABLE_NAME")
    
    # print all the first cell of all the rows
    for row in cur.fetchall():
        print row[0]
    
    db.close()
    

    当然,有数千种可能性和选择;这是一个非常基本的例子 . 您将不得不查看文档 . A good starting point .

    3 - More advanced usage

    一旦你知道它是如何工作的,你可能想要使用ORM来避免手动编写SQL并操纵你的表,因为它们是Python对象 . Python社区中最着名的ORM是SQLAlchemy .

    我强烈建议你使用它:你的生活将变得更加容易 .

    我最近发现了Python世界中的另一颗宝石:peewee . 这是一个非常精简的ORM,设置非常简单快捷,然后使用 . 它使我的小项目或独立应用程序的日子,使用像SQLAlchemy或Django这样的大工具是过度的:

    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
    

    此示例开箱即用 . 除了使用小便( pip install peewee )之外别无其他 .

  • 90

    从python连接到MySQL的最佳方法是使用MySQL Connector / Python,因为它是MySQL的官方Oracle驱动程序,用于处理Python,它适用于Python 3和Python 2 .

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

    • 使用pip安装连接器

    pip install mysql-connector-python

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

    • 使用mysql连接器python的 connect() 方法连接MySQL.pass所需的参数为 connect() 方法 . 即主机,用户名,密码和数据库名称 .

    • connect() 方法返回的连接对象创建 cursor 对象以执行SQL查询 .

    • 工作完成后关闭连接 .

    Example

    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 ("Your 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/

    Important API of MySQL Connector Python

    • 对于DML操作 - 使用 cursor.execute()cursor.executemany() 运行查询 . 然后使用 connection.commit() 将更改保留到DB

    • 要获取数据 - 使用 cursor.execute() 运行查询并使用 cursor.fetchall() ,_ cursor.fetchone()cursor.fetchmany(SIZE) 来获取数据

  • 8

    首先安装驱动程序

    pip install MySQL-python
    

    然后基本代码如下:

    #!/usr/bin/python
    import MySQLdb
    
    try:
        db = MySQLdb.connect(host="localhost",      # db server, can be a remote one 
                         db="mydb"                  # database
                         user="mydb",               # username
                         passwd="mydb123",          # password for this username
                         )        
    
        # Create a Cursor object
        cur = db.cursor()
    
        # Create a query string. It can contain variables
        query_string = "SELECT * FROM MY_TABLE"
    
        # Execute the query
        cur.execute(query_string)
    
        # Get all the rows present the database
        for each_row in cur.fetchall():
            print each_row
    
        # Close the connection
        db.close()
    except Exception, e:
        print 'Error ', e
    
  • 2

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

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

    对于python 3.3

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

    我在我的Windows 7上安装了pip,只需pip install cymysql

    (你不需要cython)快速无痛

  • 1

    这是一种方法:

    #!/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()
    

    Reference here

  • 0

    Oracle(MySQL)现在支持纯Python连接器 . 这意味着不需要安装二进制文件:它只是一个Python库 . 它被称为“连接器/ Python” .

    http://dev.mysql.com/downloads/connector/python/

  • 18

    如果你不需要MySQLdb,但是会接受任何库,我会非常非常推荐MySQL的MySQL Connector / Python:http://dev.mysql.com/downloads/connector/python/ .

    它是一个包(大约110k),纯Python,所以它是独立于系统的,并且易于安装 . 您只需下载,双击,确认许可协议即可 . 不需要Xcode,MacPorts,编译,重启......

    然后连接如下:

    import mysql.connector    
    cnx = mysql.connector.connect(user='scott', password='tiger',
                                  host='127.0.0.1',
                                  database='employees')
    
    try:
       cursor = cnx.cursor()
       cursor.execute("""
          select 3 from your_table
       """)
       result = cursor.fetchall()
       print result
    finally:
        cnx.close()
    
  • 2

    SqlAlchemy


    SQLAlchemy是Python SQL工具包和对象关系映射器,它为应用程序开发人员提供了SQL的全部功能和灵活性 . SQLAlchemy提供了一整套众所周知的企业级持久性模式,旨在实现高效,高性能的数据库访问,并采用简单的Pythonic域语言 .

    安装

    pip install sqlalchemy
    

    RAW查询

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

    ORM方式

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

相关问题