Mysql connectivity through python

Traceback (most recent call last):
File “mysqlinsert.py”, line 1, in
import mysql.connector
ImportError: No module named mysql.connector

code

import mysql.connector

mydb = mysql.connector.connect(
host=“hostname”,
user=“sqoopuser”,
passwd=“XXXX”,
database=“sqoopex”
)

I am getting No Module named mysql.connector error. hi Giri, as per your earlier update , it was installed in Jupyter. Do I need to run any other command to resolve this issue.

Hi,
mysql.connector is already installed, kindly check your hostname, password credentials please, you also need to create a cursor object from python which will point to the Mysql command.

It should be as below

import mysql.connector

db_connection = mysql.connector.connect(
host=“10.142.1.2”,
user=“sqoopuser”,
passwd=“NHkkP876rp”,
database=“sqoopex”
)

mycursor = db_connection.cursor() --> Creating a cursor object.
mycursor.execute(“show databases”) --> executing the Mysql statements, result will be stored in mycursor object.
for x in mycursor: --> Iterating through the object to get the result. as it is object.
print(x)

mycursor.execute(“show tables”) etc

I personally recommend( First Time) you to not use Command line when you are using connection to dbs from Python, it will become a bit messy to understand the syntax and indentation.

Solutions : Create a .py file write a connector file script in it, initially run this to get connect, then you can write your mysql statements inside the mycursor.execute(“show tables”) it is better and industry relevant.

Kindly have a look to the attachment for your reference.

All the best and Happy Learning with CloudxLab.

Thanks for update Satyajit. I am now able to connect mysqldatabase using python module.