To connect Python to MariaDB, you typically use a Python module specifically designed for MariaDB. The `mysql.connector` is one of the most common ones used.
Here’s a simple step-by-step process:
1. Install the MariaDB Python connector
If you do not already have the MariaDB connector, you need to install it. Use the `pip` command to install:
```
pip install mysql-connector-python
```
1. Import the mysql.connector module
Once you have the connector installed, you can import the module into your Python script like so:
```
import mysql.connector
```
1. Connect to MariaDB
Next, you can connect to MariaDB using the `connect()` function provided by the module. You need to provide your database credentials (username, password, host, database name) as arguments to the function.
```
mydb = mysql.connector.connect(
host=“localhost”,
user=“yourusername”,
passwd=“yourpassword”,
database=“mydatabase“
)
```
1. Check If Connection Was Successful
You can confirm that you have successfully connected to MariaDB by creating a cursor and executing a command.
```
mycursor = mydb.cursor()
mycursor.execute(“SELECT DATABASE”)
myresult = mycursor.fetchone()
print(“You’re connected to database: “, myresult)
```
1. Close the connection
Remember always close the connection when you are done with database operations. This is done by invoking `close()` method:
```
mydb.close()
```
Always handle the database operations within try/except block in order to catch and handle any potential errors.