Preparatory manipulations for working with SQL in Python
Let's now learn how to work with databases via Python. To do this, first of all, you need to establish a connection to the database server.
This is done using special modules. The most popular module is mysql_connector
. Let's install it in our working directory:
pip install mysql-connector-python # for Windows
pip3 install mysql-connector-python # for Linux
After installing mysql_connector
, you need to register the connection to the database in your working file. To do this, first register the import from the module of the connect
function and the Error
exception. Then create the try-except
structure to check the connection to the database. In the try-except
block, set the with
structure, which will automatically close the query after executing it. In the connect
function parameters, set the host name, user, password, and database name. The result of the connect
function is written to the connection
variable. If the connection is successful, the value of the connection
variable will be output to the console. Otherwise, an error message will be displayed:
from mysql.connector import connect, Error
try:
with connect(
host='localhost',
user='root',
password='',
database='test',
) as connection:
print(connection)
except Error as e:
print(e)
If all parameters are set correctly, the MySQLConnection object will be displayed in the console:
<mysql.connector.connection_cext.CMySQLConnection object at 0x000001D2BED35F70>
Establish a connection to your database that contains the users
table.