dedtech.info

Information about computer technology.

Grant Python Access To A MySQL Database

This blog post will explain how to grant Python access to a MySQL database. The command below will install the Python MySQL wrapper.

pip install mysql-connector-python

First, the required library has to be imported.

import mysql.connector

The function below will connect to a database using a specified hostname, username, and password.

sql = mysql.connector.connect(host="localhost", user="user", password="pass", database="exampledb")

A cursor has to be created to be able to fetch rows and columns from a table within a database. The variable rows will hold the result of the SQL query.

cursor = sql.cursor()
cursor.execute("SELECT * FROM tablename")
rows = cursor.fetchall()

A loop will print out each row that was fetched from the table.

for row in rows:
    print(row)

Lastly, cursor and sql have to be closed.

cursor.close()
sql.close()

This is what the whole source code looks like.

import mysql.connector

sql = mysql.connector.connect(host="localhost", user="user", password="pass", database="exampledb")

cursor = sql.cursor()
cursor.execute("SELECT * FROM tablename")
rows = cursor.fetchall()

for row in rows:
    print(row)

cursor.close()
sql.close()

Leave a Reply

Your email address will not be published. Required fields are marked *