Search code examples
mysqlpython-3.xpymysql

Type error in PyMySQL cursor


I have the following simple code to test my Python Mysql connection.

connection = pymysql.connect(host = "localhost",
                     user = "root",
                     passwd = "",
                     db = "bugs",
                     charset = "utf8mb4",
                     cursorclass = "pymysql.cursors.Dictcursor")

try:
    with connection.cursor() as cur:
        cur.execute('''SELECT COUNT(*) FROM tbl_firefox''')

        for row in cur.fetchall():
            print("Number of rows in firefox table:", row)
    connection.commit()
finally:
    connection.close()

When I run the code I get a type error

File "test2.py", line 31, in <module>
    with connection.cursor() as cur:
  File "C:\Program Files\Anaconda3\lib\site-packages\pymysql\connections.py", line 833, in cursor
    return self.cursorclass(self)
TypeError: 'str' object is not callable

I have been viewing similar errors in other python-mysql codes. But still no luck. If anyone could point me the bug, much appreciated.


Solution

  • Quoted fro PyMySQL:

    import pymysql.cursors
    
    # 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()
    

    It should be password other than passwd and cursorclass is not surrounded by quotes