How do I connect to a MySQL database using a python program?
First step to get The Library:
Open terminal and execute pip install mysql-python-connector
.
After the installation go the second step.
Second Step to import the library:
Open your python file and write the following code:
import mysql.connector
Third step to connect to the server: Write the following code:
conn = mysql.connector.connect(host=
you host name like localhost or 127.0.0.1
, username=your username like root
, password =your password
)
Third step Making the cursor:
Making a cursor makes it easy for us to run queries.
To make the cursor use the following code:
cursor = conn.cursor()
Executing queries:
For executing queries you can do the following:
cursor.execute(query)
If the query changes any thing in the table you need to add the following code after the execution of the query:
conn.commit()
Getting values from a query:
If you want to get values from a query then you can do the following:
cursor.excecute('SELECT * FROM
table_name') for i in cursor: print(i) #Or for i in cursor.fetchall(): print(i)
The fetchall() method returns a list with many tuples that contain the values that you requested ,row after row .
Closing the connection:
To close the connection you should use the following code:
conn.close()
Handling exception:
To Handel exception you can do it Vai the following method:
try: #Logic pass except mysql.connector.errors.Error: #Logic pass
To use a database:
For example you are a account creating system where you are storing the data in a database named blabla, you can just add a database parameter to the connect() method ,like
mysql.connector.connect(database =
database name)
don't remove other informations like host,username,password.