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 PIP location using the command line, then type the following:

Download and install "MySQL Connector":

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

Nu har du downloadet og installeret MySQL-driveren.

Test MySQL Connector

For at teste, om installationen er succesfuld eller om du har installeret "MySQL Connector", opret en Python-side med følgende indhold:

demo_mysql_test.py:

import mysql.connector

Kør Eksempel

Hvis der ikke opstår fejl ved udførelse af ovenstående kode, er "MySQL Connector" installeret og klar til brug.

Opret forbindelse

Opret først forbindelse til databasen.

Brug brugernavnet og adgangskoden fra MySQL-databasen:

demo_mysql_connection.py:

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

Kør Eksempel

Nu kan du begynde at bruge SQL-sætninger til at søge i databasen.