To connect to a MariaDB database from Python, you will need to install the mysql-connector-python
package, which is a MariaDB Connector that implements the Python Database API v2.0 (PEP 249). Once you have that installed, you can use the following steps to connect to a MariaDB database from your Python code:
Import the mysql.connector
module, which contains the connect()
function that is used to connect to a MariaDB database.
import mysql.connector
- Create a
mysql.connector.connect()
instance, which represents a connection to a MariaDB database. You will need to specify the following arguments to theconnect()
function:
host
: The hostname or IP address of the MariaDB server.user
: The username to use when connecting to the MariaDB server.password
: The password to use when connecting to the MariaDB server.database
: The name of the MariaDB database that you want to connect to.
cnx = mysql.connector.connect(
host="hostname",
user="username",
password="password",
database="database"
)
- Once the connection is established, you can use the
cnx
object to execute SQL statements and manage the connection to the MariaDB database. For example, you can create amysql.connector.cursor.MySQLCursor
object to execute SQL statements and retrieve the results of your queries:
cursor = cnx.cursor()
query = "SELECT * FROM table"
cursor.execute(query)
result = cursor.fetchall()
- When you are done working with the MariaDB database, you should close the cursor and the connection to the database using the
close()
method:
cursor.close()
cnx.close()
Comments
Post a Comment