PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python » Databases » Python MySQL Database Connection using MySQL Connector

Python MySQL Database Connection using MySQL Connector

Updated on: March 9, 2021 | 43 Comments

In this lesson, you will learn how to connect the MySQL database in Python using the ‘MySQL Connector Python‘ module. This Python MySQL tutorial demonstrates how to develop and integrate Python applications with a MySQL database server.

In Python, We can use the following modules to communicate with MySQL.

  • MySQL Connector Python
  • PyMySQL
  • MySQLDB
  • MySqlClient
  • OurSQL

Note: Above all interfaces or modules are adhere to Python Database API Specification v2.0 (PEP 249) that means the syntax, method, and way of access the database is the same in all.

PEP 249 is designed to encourage and maintain similarity between the Python modules that are used to access databases. By doing this, above all modules are following rules defined in Python Database API Specification v2.0 (PEP 249).

You can choose any of the above modules as per your requirements. The way of accessing the MySQL database remains the same. I recommend you to use any of the following two modules:-

  1. MySQL Connector Python
  2. PyMySQL

Note: This tutorial focuses on the MySQL Connector Python module. All examples are created using MySQL Connector Python.

Advantages and benefits of MySQL Connector Python: –

  • MySQL Connector Python is written in pure Python, and it is self-sufficient to execute database queries through Python.
  • It is an official Oracle-supported driver to work with MySQL and Python.
  • It is Python 3 compatible, actively maintained.

Table of contents

  • How to connect MySQL database in Python
    • Arguments required to connect
  • Create MySQL table from Python
  • Python MySQL CRUD Operation
  • Python MySQL Connection arguments list
    • Use the Dictionary to keep MySQL Connection arguments
  • Change MySQL Connection Timeout from Python
  • Connect to MySQL Using Connector Python C Extension
  • Next Steps:

How to connect MySQL database in Python

Let’s see how to connect the MySQL database in Python using the ‘MySQL Connector Python’ module.

Arguments required to connect

You need to know the following detail of the MySQL server to perform the connection from Python.

ArgumentDescription
UsernameThe username that you use to work with MySQL Server. The default username for the MySQL database is a root.
PasswordPassword is given by the user at the time of installing the MySQL server. If you are using root then you won’t need the password.
Host nameThe server name or Ip address on which MySQL is running. if you are running on localhost, then you can use localhost or its IP 127.0.0.0
Database nameThe name of the database to which you want to connect and perform the operations.

How to Connect to MySQL Database in Python

  1. Install MySQL connector module

    Use the pip command to install MySQL connector Python.
    pip install mysql-connector-python

  2. Import MySQL connector module

    Import using a import mysql.connector statement so you can use this module’s methods to communicate with the MySQL database.

  3. Use the connect() method

    Use the connect() method of the MySQL Connector class with the required arguments to connect MySQL. It would return a MySQLConnection object if the connection established successfully

  4. Use the cursor() method

    Use the cursor() method of a MySQLConnection object to create a cursor object to perform various SQL operations.

  5. Use the execute() method

    The execute() methods run the SQL query and return the result.

  6. Extract result using fetchall()

    Use cursor.fetchall() or fetchone() or fetchmany() to read query result.

  7. Close cursor and connection objects

    use cursor.clsoe() and connection.clsoe() method to close open connections after your work completes

MySQL database connection in Python
MySQL database connection in Python

Run the below query on the MySQL console if you have not created any database in MySQL. Otherwise, you can skip the below query.

Create Database in MySQL

Create database Electronics;Code language: Python (python)

Example to connect to MySQL Database in Python

import mysql.connector
from mysql.connector import Error

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='Electronics',
                                         user='pynative',
                                         password='pynative@#29')
    if connection.is_connected():
        db_Info = connection.get_server_info()
        print("Connected to MySQL Server version ", db_Info)
        cursor = connection.cursor()
        cursor.execute("select database();")
        record = cursor.fetchone()
        print("You're connected to database: ", record)

except Error as e:
    print("Error while connecting to MySQL", e)
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")
Code language: Python (python)

Output.

Connected to MySQL Server version  5.7.19
You're connected to database:  ('electronics',)
MySQL connection is closed

Points to remember

  • Catch exceptions that may occur during this process by importing the Error class from the MySQL connector module using a from mysql.connector import Error statement.
    Error class is useful to debug when we failed to connect to MySQL. For example, ACCESS DENIED ERROR when the username or password is wrong.
  • The connect() method can throw a Database error exception if one of the required parameters is wrong. For example, if you provide a database name that is not present in MySQL.
  • The is_connected() is the method of the MySQLConnection class through which we can verify is our Python application connected to MySQL.
  • At last, we are closing the MySQL database connection using a close() method of MySQLConnection class.

Create MySQL table from Python

Now you know how to connect to a MySQL server from Python, In this section, we will learn how to create a table in MySQL from Python. Let’s create table ‘Laptop’ under the ‘Electronics’ database.

import mysql.connector

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='Electronics',
                                         user='pynative',
                                         password='pynative@#29')

    mySql_Create_Table_Query = """CREATE TABLE Laptop ( 
                             Id int(11) NOT NULL,
                             Name varchar(250) NOT NULL,
                             Price float NOT NULL,
                             Purchase_date Date NOT NULL,
                             PRIMARY KEY (Id)) """

    cursor = connection.cursor()
    result = cursor.execute(mySql_Create_Table_Query)
    print("Laptop Table created successfully ")

except mysql.connector.Error as error:
    print("Failed to create table in MySQL: {}".format(error))
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")
Code language: Python (python)

Output:

Laptop Table created successfully 
MySQL connection is closed

Python MySQL CRUD Operation

Also, learn how to execute various MySQL operations from Python by referring to the following articles.

Click on each tutorial to study operations in detail.

  • Insert rows into MySQL table from Python: Insert a single and multiple rows into the MySQL table. Also, learn how to use Python variables in the parameterized query to insert dynamic data into a table.
  • Select rows from MySQL table using Python: Execute a SQL SELECT query from a Python application to fetch rows from MySQL table. Also, learn how to process SELECT query results, Fetch all rows or single rows from the table, and count total rows of a table.
  • Update rows of MySQL table from Python: Update a single row, multiple rows, a single column, and various columns. Additionally, learn how to use python variables in the parameterized query to update table data.
  • Delete table rows from Python: Delete a single row, multiple rows, a single column, and various columns. Also, learn to Delete all Rows, Delete tables, and an entire database from MySQL using python.
  • Execute MySQL stored procedures from Python and learn how to pass IN and OUT parameters to the MySQL stored procedure.
  • Python MySQL Parameterized Query and Prepared Statement: Learn to use Parameterized Queries or Prepared Statement to use Python variables in the SQL query to pass dynamic data to MySQL table.
  • Python MySQL Commit and Rollback to Manage Transactions: Manage MySQL database transactions from Python to maintain the ACID property of MySQL transactions using the commit() and rollback() methods.
  • Python Database Connection Pooling With MySQL: Learn to create and use a connection pool to increase the performance of your Python MySQL applications.
  • Python MySQL BLOB Insert and Retrieve digital data: Learn to insert or fetch any digital information such as a file, image, video, or song as blob data into MySQL table from Python.

Python MySQL Connection arguments list

We already discussed the four mandatory arguments required to connect the MySQL Server.

Let see what other connection arguments we can use to communicate with the MySQL server from Python. Below is the list of all other connection arguments and their meaning.

  • port: The TCP/IP port of the MySQL server. This value must be an integer. We can specify the different port number if the MySQL server is listening to a different port. The default value for this port argument is 3306.
  • use_unicode: Specify whether to use Unicode or not. The default value is True.
  • charset: MySQL character set to use, character set variables relate to a client’s interaction with the server. There are almost 30 to 40 charset MySQL server supports. The default value of the charset argument is “utf8″.
  • auto-commit: Set it to true if you want to auto-commit transactions. If you wish to manage transactions in MySQL from Python, you need to set this value true or false. The default value is False, i.e., the changes are not committed to the database. You need to explicitly call a commit method to persist your changes in the database.
  • get_warnings: To fetch warning, this is helpful to know the connection is established but with warnings. The default value is False.
  • raise_on_warnings: Set it when you want to raise an exception on warnings. The Default value is False.
  • connection_timeout (connect_timeout*) : Timeout for the TCP and Unix socket connections. The connection terminates after this timeout expired.
  • buffered: If true, the cursor objects fetch the results immediately after executing queries. The default value is False.
  • raw: If true, MySQL results are returned as-is rather than converting into Python types. The default value is False. You can set it to true if you want a query result in MySQL type.
  • force_ipv6: When setting to True, uses IPv6 when an address resolves to both IPv4 and IPv6. By default, IPv4 is used in such cases. The default value for this argument is false.
  • pool_name: It is the Connection pool name that you are creating or using.
  • pool_size: Connection pool size that you want to create. The default value is 5.
  • pool_reset_session: Reset session variables when the connection is returned to the pool. The default is True.
  • use_pure: Specify whether to use pure Python or C Extension. If use_pure=False, then a pure Python module is used; otherwise, it connects MySQL using C extension. Moreover, if C Extension is not available, MySQL Connector Python automatically falls back to the pure Python implementation.
  • unix_socket: The location of the Unix socket file. These enable communication between two processes.
  • auth_plugin: Authentication plugin to use, Added in 1.2.1.
  • collation: MySQL collation to use. You can use the collation that you set while installing MySQL Server. The default value is utf8_generalW_chiich.
  • sql_mode: Set the sql_mode session variable at connection time.

Use the Dictionary to keep MySQL Connection arguments

Furthermore, let see how to use a dictionary to store all of these connection arguments.

If you have lots of connection arguments, it’s best to keep them in a dictionary and use the ** operator.  for example, you know you require a minimum of four arguments  (i.e., username, password, hostname, database name) to connect MySQL.

If you have lots of connection arguments, it’s best to keep them in a dictionary and use the ** operator. In exceptional cases, we need more than four arguments in the connect method to connect the MySQL database. Let’s understand this. For example, below are three more connection arguments we can use in the connect() method.

  1. connection_timeout – Timeout for the TCP and Unix socket connections
  2. auto_commit – Whether to auto-commit transactions. The default is false
  3. pool_size – Connection pool size if you want to use connection pooling.

You can use many other connection arguments as per your need, add them all in a dictionary, and pass a dictionary to connect() method. Let’s demonstrate it in the below example.

import mysql.connector
from mysql.connector import Error

try:
    connection_config_dict = {
        'user': 'pynative',
        'password': 'pynative@123',
        'host': '127.0.0.1',
        'database': 'Electronics',
        'raise_on_warnings': True,
        'use_pure': False,
        'autocommit': True,
        'pool_size': 5
    }
    connection = mysql.connector.connect(**connection_config_dict)

    if connection.is_connected():
        db_Info = connection.get_server_info()
        print("Connected to MySQL Server version ", db_Info)
        cursor = connection.cursor()
        cursor.execute("select database();")
        record = cursor.fetchone()
        print("Your connected to database: ", record)

except Error as e:
    print("Error while connecting to MySQL", e)
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")
Code language: Python (python)

Change MySQL Connection Timeout from Python

Sometimes we need to change the connection timeout value if we read or insert extensive data to the MySQL server. Connection terminates if the request takes more time than this value.

Use a connection_timeout argument of MySQL connector Python to manage the timeout issues by increasing the timeout value.

The connection_timeout is the timeout value in second for the TCP and Unix socket connections. This time denotes the number of seconds the MySQL server waits to fulfill the current request.

You can also set the following Parameters of the MySQL server by executing SQL query from Python to handle the connection timeout issue. Change the following parameters’ value only when the connection_timeout argument alone can’t control the timeout issue.

  • interactive_timeout: The number of seconds the server should wait for activity on an interactive connection before closing it.
  • wait_timeout – Number of seconds the server should wait for activity on a connection before closing it.

Example

import mysql.connector
from mysql.connector import Error

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='Electronics',
                                         user='pynative',
                                         password='pynative@#29', connection_timeout=180)

    if connection.is_connected():
        db_Info = connection.get_server_info()
        print("Connected to MySQL database... MySQL Server version on ", db_Info)

        cursor = connection.cursor()
        # global connection timeout arguments
        global_connect_timeout = 'SET GLOBAL connect_timeout=180'
        global_wait_timeout = 'SET GLOBAL connect_timeout=180'
        global_interactive_timeout = 'SET GLOBAL connect_timeout=180'

        cursor.execute(global_connect_timeout)
        cursor.execute(global_wait_timeout)
        cursor.execute(global_interactive_timeout)

        connection.commit()

except Error as e:
    print("Error while connecting to MySQL", e)
finally:
    # closing database connection.
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")Code language: Python (python)

As you can see, I have set all connection timeout values to 180 seconds, i.e., 3 min in the above program.

Connect to MySQL Using Connector Python C Extension

Python connector module has a C Extension interface to connect the MySQL database. The use_pure connection argument determines whether to connect to MySQL using a pure Python interface or a C Extension.

The default value of use_pure is False means it uses the pure Python implementation to connect that we already discussed. The below example demonstrates how to connect using a C extension.

import mysql.connector
from mysql.connector import Error

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='Electronics',
                                         user='pynative',
                                         password='pynative@#29', use_pure=True)

    if connection.is_connected():
        db_Info = connection.get_server_info()
        print("Connected to MySQL database... MySQL Server version on ", db_Info)
except Error as e:
    print("Error while connecting to MySQL", e)
finally:
    if connection.is_connected():
        connection.close()
        print("MySQL connection is closed")
Code language: Python (python)

Next Steps:

To practice what you learned in this article, Please solve a Python Database Exercise project to Practice and master the Python Database operations.

I have created a Hospital Information System exercise using Python and MySQL. This Exercise has six questions. I have provided the required tables so you can proceed directly to solve the problems of this Exercise.

That’s it, Folks. Let me know your comments in the section below.

Filed Under: Python, Python Databases

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Databases

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Comments

  1. ImageJemin Ajudiya says

    July 18, 2023 at 11:38 am

    Hello sir there are two syntax error in tutorial ;

    7. Close cursor and connection objects
    use cursor.clsoe() and connection.clsoe() method to close open connections after your work completes

    correction: cursor.close() and connection.close()

    Reply
  2. ImageKARTHIKEYAN KESAVAN says

    January 20, 2023 at 10:40 pm

    i got this error
    Can’t connect to MySQL server on ‘%-.100s:%u’ (%s) (Warning: %u format: a real number is required, not str)

    i am new to python

    Reply
    • Imagejust helping says

      September 17, 2023 at 6:50 pm

      its saying that your input has to be in integer for use ‘int’

      Reply
  3. Imagebhakti says

    February 23, 2022 at 5:29 am

    I would like to learn Python. Do you offer Python classes?

    Reply
    • ImageTanmay says

      June 11, 2024 at 6:58 pm

      Have you ever learned to **look up**? If you do that, there is a clear, bold named section “Learn Python”… more?

      Reply
  4. ImageJulian Pichler says

    July 20, 2021 at 2:05 am

    Hey, i try to execute a stored procedure which write a new line in a table. i think to execute the procedure, i need “use database;” and “call procedure;”. But when i write two selects in the mySql_Create_Table_Query = “”” “””, the programm returns “failed to execute: use multi=True when executing multiple statements”. I know its very self explanatory but i dont get it. I tryed to put the “multi=True” after the “password=’xxx’, ” but this dosn’t work. Mayby you can help me.

    Reply
  5. ImageFarzad says

    May 14, 2021 at 12:28 am

    Does anyone know any python mysql module that supports connection pooling with connection idle timeout? All the libraries I have tried, do not have any option to set the idle timeout for idle connections sitting in the pool. I want to be able to remove the idle connections from the pool after a certain timeout.

    Reply
  6. ImageCoder Dude says

    November 20, 2020 at 7:33 am

    When you call the connect function, could you insert the host IP as the host to allow for remote connections to the database?

    Reply
    • ImageVishal says

      November 21, 2020 at 10:01 am

      Yes you can

      Reply
  7. ImageViktoras says

    August 9, 2020 at 4:57 pm

    You my hero! <3

    Reply
  8. ImageThomas says

    June 16, 2020 at 7:31 am

    hey there is syntax and usage errors together… if you want to use C extension, you have to set “use_pure=False” not “use_pure=true”… If you want to use pure python, you have to set “use_pure=True” not “use_pure=true”… “use_pure=true” will rise “NameError”

    Reply
  9. ImageShilpa Thomas says

    May 12, 2020 at 4:17 pm

    I need to input the database IP, username and password while run the file.
    How to do that ?

    Reply
  10. ImageMohammed Al Ameen says

    May 7, 2020 at 4:27 pm

    Please, can you explain how I can connect to an online database too, I’ve successfully practiced it on my localhost, thanks to the article you posted here

    Reply
    • ImageVishal says

      May 7, 2020 at 8:22 pm

      Hey Mohammed, Instead of localhost please provide the URL where your database is present

      Reply
  11. Imagesaru says

    May 7, 2020 at 11:30 am

    Hi Vishal,
    Great content in your web site. Really help full for python developers.
    Could you help me to resolve one issue while writing connection code .I am getting ” ModuleNotFoundError: No module named ‘dns’ ”
    have tried pip install dnspython
    Thanks

    Reply
    • ImageVishal says

      May 7, 2020 at 8:24 pm

      Thank you Saru, Please read this answer it will help.

      Reply
  12. ImageJuanma says

    April 20, 2020 at 1:35 pm

    Hey, Vishal, thanks for this tutorial.
    just a comment: if Python couldn’t connect to mysql, connection would not be defined in the finally block. To fix that, I added
    connection=None
    before the try and changed the condition in the finally to

    if (connection is not None and connection.is_connected()) 

    best,
    Juanma

    Reply
    • ImageVishal says

      April 22, 2020 at 10:40 am

      Great

      Reply
      • ImageJB says

        September 5, 2022 at 10:27 pm

        Agree and would be great to amend your code accordingly

        Reply
  13. ImageFabiano Souza de Oliveira says

    February 5, 2020 at 7:43 pm

    What is the best way to dynamically define the MySQL connection between local host and production?

    Do we have something similar to PHP’s $ _SERVER [‘HTTP_HOST’] to check if we are on a production server or localhost?

    Reply
  14. ImageGrashal V says

    November 9, 2019 at 11:51 pm

    Thank you sir for this wonderful explanation. But please help me with my project. I have created a login register application using Tkinter and Python connectivity with MySQL database. I have successfully created the register page but need your help with login. the details with which I registered go to a table named customers in my MySql database. When I login I want to login with those details but I can’t code that program. I have tried zomething like this :-

    def loginfunc():
              userfield=e1.get()
              passfield=e2.get()
              cursor2=con.cursor(buffered=True)
              cursor3=con.cursor(buffered=True)
              usersql=("SELECT User_ID from customers WHERE User_ID = '%s' ")
              passsql=("SELECT Password from customers WHERE Password = '%s'; ")
              cursor2.execute(usersql,userfield)
              cursor3.execute(passsql,passfield)
              userverify=list(cursor2.fetchall())
              passverify=list(cursor3.fetchall())
    
              if(userfield in userverify) and (passfield in passverify):
                        messagebox.showinfo("Login","Success")
              else:
                        messagebox.showinfo("Login","Fail")
    

    Please help!

    Reply
  15. ImageSteve says

    October 27, 2019 at 9:47 pm

    Hi Vishal,

    I am just getting started, but your tutorial looks very helpful. Two comments:
    1) A minor typo. You mixed up your homophones — “your” and “you’re” — in the first script:

    `print("You're connected to database: ", record)`
    

    2) In addition to `mysql> create database Electronics;` I needed:

    `mysql> CREATE USER pynative@localhost IDENTIFIED BY 'pynative@#29';`
    `mysql> GRANT ALL ON electronics.* TO pynative@localhost;`
    

    Perhaps that is because I chose a password for ‘root’ when I installed MySQL 8.0.18.

    Thanks. Looking forward to the rest of the tutorial.

    Reply
    • ImageVishal says

      October 27, 2019 at 10:47 pm

      Thank you Steve for your feedback and suggestions.

      Reply
  16. ImageBronco says

    October 16, 2019 at 11:02 pm

    Hi Vishal,

    Excellent work!!
    Need your help on this:
    Any idea of how multiple connection can be stored in a dictionary?

    cnx={}
    cnx.update({'host1']:mysql.connector.connect(host='host1',...
    cnx.update({'host2']:mysql.connector.connect(host='host2',...
    

    Thanks,
    Bronco

    Reply
    • ImageVishal says

      October 17, 2019 at 8:51 am

      Hi Bronco.

      you can try this:

      import mysql.connector
      from mysql.connector import Error
      
      connection_dic = {}
      
      try:
          connection_dic['host1'] = mysql.connector.connect(host='host1', database='Electronics', user='root', password='pynative@#29')
      
          connection_dic['host2'] = mysql.connector.connect(host='host2', database='Electronics', user='root', password='pynative@#29')
      
          sql_select_Query = "select * from Laptop"
          cursor = connection_dic.get("host1").cursor()
          cursor.execute(sql_select_Query)
          records = cursor.fetchall()
          print("Total number of rows in Laptop is: ", cursor.rowcount)
      
          sql_select_Query = "select * from Laptop"
          cursor = connection_dic.get("host2").cursor()
          cursor.execute(sql_select_Query)
          records = cursor.fetchall()
          print("Total number of rows in Laptop is: ", cursor.rowcount)
      
      except Error as e:
          print("Error reading data from MySQL table", e)
      finally:
      	#check connection is open or not before closing
          if (connection_dic.get("host1").is_connected()):
              connection_dic.get("host1").close()
              connection_dic.get("host2").close()
              cursor.close()
      

      Or instead of creating multiple connections and storing in the dictionary. you can create a common connection method and call it from multiple locations with required connection arguments. For example

      import mysql.connector
      from mysql.connector import Error
      
      def mySQLConnect(host, database, user, password):
          try:
              connection = mysql.connector.connect(host=host, database=database, user=user, password=password)
          except Error as e:
              print("Error creating connection", e)
      
          return connection
      
      def closeConnection(connection):
          if (connection.is_connected()):
              connection.close()
              print("MySQL connection is closed")
      
      sql_select_Query = "select * from Laptop"
      connection = mySQLConnect('host1','Electronics','root', 'pynative@#29')
      cursor = connection.cursor()
      cursor.execute(sql_select_Query)
      records = cursor.fetchall()
      print("Total number of rows in Laptop is: ", cursor.rowcount)
      closeConnection(connection)
      
      sql_select_Query = "select * from Laptop"
      connection = mySQLConnect('host2','Electronics','root', 'pynative@#29')
      cursor = connection.cursor()
      cursor.execute(sql_select_Query)
      records = cursor.fetchall()
      print("Total number of rows in Laptop is: ", cursor.rowcount)
      closeConnection(connection)
      
      
      Reply
      • ImageBronco says

        October 25, 2019 at 3:35 am

        Hi Vishal,

        Your (1st) solution looks fantastic. I will definitely use it!

        Thanks,
        Bronco

        Reply
        • ImageVishal says

          October 25, 2019 at 3:36 pm

          Bronco, I am glad it helped you.

          Reply
  17. ImageCP says

    October 13, 2019 at 10:53 pm

    I’ve just solved a fundamental issue experienced why trying to follow your tutorial. Saving the sample code in a local file and then executing,

    python3 BasicConnection.py

    would yield an error message that reads,

    Traceback (most recent call last):
    File “BasicConnection.py”, line 1, in
    import mysql.connector
    ModuleNotFoundError: No module name ‘mysql’

    which, it would appear, was caused because the “pip” command you quote has added the MySQL module, but only to my python2 environment and not python3.

    Your tutorial does not state whether it is appropriate for python2 or 3 and your quote of the pip command does not differentiate how to use that tool based on whether the user is trying to operate the Python2 or Python3 environment.

    All told, whilst the basics of what you are trying to convey is likely quite sound, your failure to correctly set context, to explain the relevant distinction of environments, seems in retrospect to be a bit of an omission. You might want to extend the article to make a clearer distinction of version dependencies.

    Reply
  18. ImageIlyas says

    July 26, 2019 at 10:07 am

    Hello Vishal,
    I have followed every step up to “After connecting to MySQL Server, you should get below output.” However, I see a blank screen when I refresh the browser. Any suggestions as to what might be wrong in my configurations?

    Reply
    • ImageVishal says

      July 26, 2019 at 9:14 pm

      Hi Ilyas, can you please provide me your code. so I can suggest

      Reply
  19. ImageIgor says

    July 21, 2019 at 11:00 pm

    Hello
    Help is needed.
    What the fragment of the database connection program will look like.
    The base is physically located on disk C:\Shop\Shop.mdf and created earlier in
    Microsoft SQL Server 2012
    Thank.

    Reply
  20. ImageMUS says

    June 11, 2019 at 11:34 pm

    thanks

    Reply
  21. ImageMiguel says

    January 6, 2019 at 11:59 pm

    I keep on getting this error : “Import error : No module named mysql”
    Any tips would be appreciated!

    Reply
    • ImageVishal says

      January 7, 2019 at 12:28 am

      Are you using mysql connector python? or tell me the module name. you need to install DB module using pip

      Reply
      • ImageMiguel says

        January 7, 2019 at 2:22 am

        I am using the module you had recommended.
        This is the exact error :

        Traceback (most recent call last):
          File "/home/pi/Desktop/mysql-test.py", line 1, in 
            import mysql.connector
          File "/usr/lib/python3/dist-packages/thonny/backend.py", line 317, in _custom_import
            module = self._original_import(*args, **kw)
        ImportError: No module named 'mysql'
        
        Reply
  22. ImageBody says

    December 26, 2018 at 1:04 am

    I keep getting mysql.connector.errors.ProgrammingError: 1698 (28000): Access denied for user. Any troubleshooting tips?

    Reply
    • ImageVishal says

      December 26, 2018 at 6:03 am

      Please check permissions. you can refer to Stackoverflow access denied for localhost

      Reply
  23. ImageUyin says

    December 18, 2018 at 5:50 am

    How to connect mysql from my PC using python?

    Reply
    • ImageVishal says

      December 18, 2018 at 8:46 am

      Hey Uyin,

      Please refer to this Steps to connect MySQL Database
      Are you facing any specific problems?

      Reply
      • ImageUyin says

        December 18, 2018 at 2:42 pm

        Yes..i cannot connect my db from my laptop..i use shared hosting..i think need hosting login..

        Host = 'www.mywebsite.com'
        user = 'db_user'
        password = 'db_password'
        host_login=?
        host_password =?
        
        Reply
        • ImageVishal says

          December 22, 2018 at 8:15 pm

          Yes you need hosting domain name or ip

          Reply
  24. ImageJason says

    July 14, 2018 at 3:31 pm

    Thank you for such informative article with deatiled explanations

    Reply
    • ImageVishal says

      July 14, 2018 at 11:26 pm

      I am glad you liked it

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Databases
TweetF  sharein  shareP  Pin

  Python MySQL

  • Python MySQL Connection Guide
  • Python MySQL Insert
  • Python MySQL Select
  • Python MySQL Update
  • Python MySQL Delete
  • Call MySQL Stored Procedure
  • Python MySQL Parameterized Query
  • Python MySQL Transactions
  • Python MySQL Connection Pooling
  • Python MySQL BLOB
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2025 pynative.com

Advertisement