Python MySQL

Python can be used in database applications.

MySQL is one of the most popular databases.

MySQL Database

To be able to test the code examples in this tutorial, you should install MySQL on your computer.

Download the free MySQL database here:https://www.mysql.com/downloads/.

Install MySQL Driver

Python requires the MySQL driver to access the MySQL database.

In this tutorial, we will use the driver "MySQL Connector".

We recommend using PIP to install "MySQL Connector".

PIP is likely already installed in the Python environment.

Navigate to the command line location of PIP and enter the following content:

Download and install "MySQL Connector":

C:\...\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install mysql-connector

Jetzt haben Sie den MySQL-Treiber heruntergeladen und installiert.

Testen Sie den MySQL Connector

Um zu testen, ob die Installation erfolgreich war oder ob Sie "MySQL Connector" installiert haben, erstellen Sie eine Python-Seite mit folgendem Inhalt:

demo_mysql_test.py:

import mysql.connector

Führen Sie das Beispiel aus

Falls keine Fehler bei der Ausführung des obigen Codes auftreten, ist "MySQL Connector" installiert und bereit zum Einsatz.

Erstellen Sie die Verbindung

Erstellen Sie zunächst eine Verbindung zur Datenbank.

Verwenden Sie den Benutzernamen und das Passwort aus der MySQL-Datenbank:

demo_mysql_connection.py:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword"
)
print(mydb)

Führen Sie das Beispiel aus

Jetzt können Sie mit SQL-Anweisungen Datenbanken abfragen.