07-27-2023, 12:24 PM
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 [
2. 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.
3. Create `cursor` object from connection object returned by `connect()`method to execute SQL queries.
4. 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 - [
**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
[1]:
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 [
[To see links please register here]
][1]2. 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.
3. Create `cursor` object from connection object returned by `connect()`method to execute SQL queries.
4. 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 - [
[To see links please register here]
][2]**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
[1]:
[To see links please register here]
[2]:[To see links please register here]