How do I connect to a MySQL Database in Python?

后端 未结 25 1517
眼角桃花
眼角桃花 2020-11-21 07:43

How do I connect to a MySQL database using a python program?

25条回答
  •  难免孤独
    2020-11-21 08:26

    for Python3.6 I found two driver: pymysql and mysqlclient. I tested the performance between them and got the result: the mysqlclient is faster.

    below is my test process(need install python lib profilehooks to analyze time elapse:

    raw sql: select * from FOO;

    immediatly execute in mysql terminal: 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()
    

    here's the pymysql profile:


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

    here's the mysqlclient profile:

    So, it seems that mysqlclient is much faster than pymysql

提交回复
热议问题