How do I connect to a MySQL Database in Python?

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

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

25条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 08:12

    Best way to connect to MySQL from python is to Use MySQL Connector/Python because it is official Oracle driver for MySQL for working with Python and it works with both Python 3 and Python 2.

    follow the steps mentioned below to connect MySQL

    1. install connector using pip

      pip install mysql-connector-python

    or you can download the installer from https://dev.mysql.com/downloads/connector/python/

    1. Use connect() method of mysql connector python to connect to MySQL.pass the required argument to connect() method. i.e. Host, username, password, and database name.

    2. Create cursor object from connection object returned by connect()method to execute SQL queries.

    3. close the connection after your work completes.

    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 ("You're 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()
    

    Reference - https://pynative.com/python-mysql-database-connection/

    Important API of MySQL Connector Python

    • For DML operations - Use cursor.execute() and cursor.executemany() to run query. and after this use connection.commit() to persist your changes to DB

    • To fetch data - Use cursor.execute() to run query and cursor.fetchall(), cursor.fetchone(), cursor.fetchmany(SIZE) to fetch data

提交回复
热议问题