What do these words mean?
MySQL is a popular database system. A database is a store for information, like a filing cabinet.
Python is an easy programming language. A programming language is a way to give instructions to a computer.
A connector is a helper library. It lets Python and MySQL understand each other. It works like a translator.
Before you start
- You need Python 3 on your computer or server.
- You need a database, a database user and its password. Make them in your control panel.
- If you connect from outside the server, ask Hostvento support to allow your IP address (the number that names your internet connection).
Step 1: install the connector
Open a terminal and type:
pip install mysql-connector-python
This downloads and installs the MySQL connector for Python.
Step 2: write the program
- Open a text editor.
- Paste this code. Use your own details:
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="your_user",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
print(cursor.fetchone())
cursor.close()
conn.close()
- Save the file as
test_db.py.
The code does these jobs. It opens a connection with your login. It asks MySQL for its version number. It prints the answer. Then it closes the connection.
Step 3: run it
python test_db.py
This runs your program. If it works, you see the MySQL version. If you get an error, read the message. It tells you what is wrong.
Common errors
- Access denied: the user name or password is wrong, or the user has no rights on that database.
- Can't connect: the host is wrong, or remote access is not allowed.
- Unknown database: the database name has a typo.
Quick recap
- Install the connector with
pip install mysql-connector-python. - Use
mysql.connector.connectwith host, user, password and database. - Run a small query to test, then close the connection.
- Check the host and rights if you see an error.