Python and MySQL: is there an alternative to MySQLdb?

前端 未结 8 1400
挽巷
挽巷 2021-02-05 13:09

Is there a module written purely in Python that will allow a script to communicate with a MySQL database? I\'ve already tried MySQLdb without success. It requires too much: GCC,

8条回答
  •  时光取名叫无心
    2021-02-05 13:56

    I had the problem that I wanted to write code which work for Python 2 and Python 3. I found pymysql to fit perfectly. I did not have to adjust code to switch from MySQLdb to pymysql

    Installation

    $ pip install PyMySQL
    

    If you don't have admin rights:

    $ pip install -u PyMySQL
    

    Usage

    The usage is the same as for MySQLdb:

    SELECT

    import pymysql
    import pymysql.cursors
    connection = pymysql.connect(host=mysql['host'],
                                 user=mysql['user'],
                                 passwd=mysql['passwd'],
                                 db=mysql['db'],
                                 cursorclass=pymysql.cursors.DictCursor)
    cursor = connection.cursor()
    sql = ("SELECT `id`, `formula_in_latex` FROM `wm_formula` "
           "WHERE `is_important` = 1 "
           "AND id != 1 "  # exclude trash class
           "ORDER BY `id` ASC")
    cursor.execute(sql)
    formulas = cursor.fetchall()
    

    INSERT

    import pymysql
    connection = pymysql.connect(host=mysql['host'],
                                 user=mysql['user'],
                                 passwd=mysql['passwd'],
                                 db=mysql['db'])
    cursor = connection.cursor()
    cursor.execute("INSERT INTO `toys` (`id`, `arrival`, `duration`) "
                   "VALUES ('1', '2014-12-01', '123');")
    connection.commit()
    

提交回复
热议问题