Mysql python package install

How to connect to MySQL using Python

Python provides several ways to connect to a MySQL database and process data. This article describes three methods.

The MySQL databases and users must already exist before you can use any of the following methods. For information about how to manage MySQL databases using cPanel, please see this article.

Connecting to MySQL using Python

Before you can access MySQL databases using Python, you must install one (or more) of the following packages in a virtual environment:

  • mysqlclient: This package contains the MySQLdb module. It is written in C, and is one of the most commonly used Python packages for MySQL.
  • mysql-connector-python: This package contains the mysql.connector module. It is written entirely in Python.
  • PyMySQL: This package contains the pymysql module. It is written entirely in Python.

All three of these packages use Python’s portable SQL database API. This means that if you switch from one module to another, you can reuse almost all of your existing code (the code sample below demonstrates how to do this).

Setting up the Python virtual environment and installing a MySQL package

To set up the Python virtual environment and install a MySQL package, follow these steps:

  1. Log in to your account using SSH.
  2. To create a virtual environment, type the following commands:
  • The virtualenv command creates a virtual environment named sqlenv, and subsequent commands in this procedure assume that the environment is named sqlenv. You can use any environment name you want, but make sure you replace all occurrences of sqlenv with your own environment name.
  • If you are running an alternate Python version (for example, you manually configured a newer Python version for your account as described in this article), you can specify that version for the virtual environment. For example, to install a user-configured version of Python 3.8 in the virtual environment, you could use the following command:
virtualenv -p /home/username/bin/python3.8 sqlenv

The command prompt now starts with (sqlenv) to indicate that you are working in a Python virtual environment. All of the following commands in this procedure assume that you are working within the virtual environment. If you log out of your SSH session (or deactivate the virtual environment by using the deactivate command), make sure you reactivate the virtual environment before following the steps below and running the sample code.

pip install mysql-connector-python
Code sample

After you install a MySQL package in the virtual environment, you are ready to work with actual databases. The following sample Python code demonstrates how to do this, as well as just how easy it is to switch between the different SQL package implementations. The sample code works with Python 2.7 and Python 3.x.

In your own code, replace username with the MySQL database username, password with the database user’s password, and dbname with the database name:

#!/usr/bin/python from __future__ import print_function hostname = 'localhost' username = 'username' password = 'password' database = 'dbname' # Simple routine to run a query on a database and print the results: def doQuery( conn ) : cur = conn.cursor() cur.execute( "SELECT fname, lname FROM employee" ) for firstname, lastname in cur.fetchall() : print( firstname, lastname ) print( "Using mysqlclient (MySQLdb):" ) import MySQLdb myConnection = MySQLdb.connect( host=hostname, user=username, passwd=password, db=database ) doQuery( myConnection ) myConnection.close() print( "Using mysql.connector:" ) import mysql.connector myConnection = mysql.connector.connect( host=hostname, user=username, passwd=password, db=database ) doQuery( myConnection ) myConnection.close() print( "Using pymysql:" ) import pymysql myConnection = pymysql.connect( host=hostname, user=username, passwd=password, db=database ) doQuery( myConnection ) myConnection.close()

This example creates a series of Connection objects that opens the same database using different MySQL modules. Because all three MySQL modules use the portable SQL database API interface, they are able to use the code in the doQuery() function without any modifications.

When you have a Connection object associated with a database, you can create a Cursor object. The Cursor object enables you to run the execute() method, which in turn enables you to run raw SQL statements (in this case, a SELECT query on a table named employee).

As you can see, Python’s portable SQL database API makes it very easy to switch between MySQL modules in your code. In the sample above, the only code changes necessary to use a different module are to the import and connect statements.

More Information

  • For more information about Python’s portable SQL database API, please visit https://www.python.org/dev/peps/pep-0249.
  • For more information about the mysqlclient package, please visit https://pypi.org/project/mysqlclient.
  • For more information about the mysql-connector-python package, please visit https://pypi.python.org/pypi/mysql-connector-python.
  • For more information about the PyMySQL package, please visit https://pypi.python.org/pypi/PyMySQL.

Источник

Mysql python package install

У библиотеки есть весьма простая, понятная документация и большое комьюнити .

Создадим файл main.py, в котором будет происходить вся магия и импортируем в него ранее установленный модуль:

Подключение к БД

Первым делом нам нужно подключиться к базе. Создадим объект класса pymysql, вызовем у него метод connect и передадим в него параметры для подключения к нашей базе данных (БД):

import pymysql connection = pymysql.connect( host='127.0.0.1', port=3306, user='first_user', password='qwerty', database='db_name', cursorclass=pymysql.cursors.DictCursor ) 
  • host: если ваша БД находится на локальной машине, то его значение будет localhost , либо 127.0.0.1, либо IP адрес хостинга, на котором вы развернули СУБД
  • port: стандартный 3306
  • user: это логин пользователя
  • password: пароль
  • db_name: имя нашей базы данных

Обернем код в блок try/except, в блоке try будем подключаться к БД, а в блоке except будем выводить в терминал возможные ошибки:

import pymysql try: connection = pymysql.connect( host='127.0.0.1', port=3306, user='first_user', password='qwerty', database='db_name', cursorclass=pymysql.cursors.DictCursor ) print("successfully connected. ") print("#" * 20) except Exception as ex: print("Connection refused. ") print(ex) 

После работы с базой рекомендуется закрывать соединение. Создадим ещё один блок try/finally, внутри блока try мы будем писать наши запросы к БД, а внутри блока finally будем закрывать наше соединение:

import pymysql try: connection = pymysql.connect( host='127.0.0.1', port=3306, user='first_user', password='qwerty', database='db_name', cursorclass=pymysql.cursors.DictCursor ) print("successfully connected. ") print("#" * 20) try: pass finally: connection.close() except Exception as ex: print("Connection refused. ") print(ex) 

Чтобы начать работать с MySQL, нам нужно создать объект cursor. Это объект, который содержит в себе различные методы для проведения SQL команд. М ы можем как просто положить его значение в переменную cursor = connection.cursor() , так и воспользоваться контекстным менеджером with. Мне второй вариант нравится больше, так как выглядит лаконичней, да и документация подсказывает нам, как правильно работать с библиотекой:

 import pymysql try: connection = pymysql.connect( host='127.0.0.1', port=3306, user='first_user', password='qwerty', database='db_name', cursorclass=pymysql.cursors.DictCursor ) print("successfully connected. ") print("#" * 20) try: # create table with connection.cursor() as cursor: pass finally: connection.close() except Exception as ex: print("Connection refused. ") print(ex) 

Теперь давайте создадим простую таблицу, на которой сегодня потренируемся. Создаем переменную create_table_query и пишем запрос.

Создать таблицу users со следующими строками:

# create table with connection.cursor() as cursor: create_table_query = "CREATE TABLE `users`(id int AUTO_INCREMENT," \ " name varchar(32)," \ " password varchar(32)," \ " email varchar(32), PRIMARY KEY (id));" 

Для того чтобы выполнить запрос на создание таблицы, вызываем у cursor метод execute, и передаем в него наш запрос. Выведем в print сообщение об успешном исполнении:

# create table with connection.cursor() as cursor: create_table_query = "CREATE TABLE `users`(id int AUTO_INCREMENT," \ " name varchar(32)," \ " password varchar(32)," \ " email varchar(32), PRIMARY KEY (id));" cursor.execute(create_table_query) print("Table created successfully") 

Добавление данных в таблицу

Таблицу мы создали, теперь давайте заполним её данными. За добавление данных в таблицу в SQL отвечает метод INSERT. Пишем запрос. Дословно говорим:

Вставить в таблицу users, перечисляем поля, которые хотим заполнить, а затем данные, которыми мы хотим наполнить запись в таблице.

Например, у нас будет пользователь Анна, с паролем qwerty и почтой от gmail:

# insert data with connection.cursor() as cursor: insert_query = "INSERT INTO `users` (name, password, email) VALUES ('Anna', 'qwerty', 'anna@gmail.com');" 

Вызываем метод execute у cursor и передаем в него наш запрос. Для того чтобы наши данные занеслись в таблицу и сохранились там, нам нужно закоммитить или зафиксировать наш запрос. Вызываем метод commit у объекта connection:

# insert data with connection.cursor() as cursor: insert_query = "INSERT INTO `users` (name, password, email) VALUES ('Anna', 'qwerty', 'anna@gmail.com');" cursor.execute(insert_query) connection.commit() 

Теперь в нашей таблице создалась одна запись с пользователем Анна.

Извлечение данных из таблицы

Напишем запрос на извлечение всех данных из таблицы. Звездочка в данном запросе забирает все, что есть в таблице:

# select all data from table with connection.cursor() as cursor: select_all_rows = "SELECT * FROM `users`" cursor.execute(select_all_rows) 

У cursor есть замечательный метод fetchall, который извлекает из таблицы все строки. Нам лишь остается пробежаться по ним циклом и распечатать.

# select all data from table with connection.cursor() as cursor: select_all_rows = "SELECT * FROM `users`" cursor.execute(select_all_rows) rows = cursor.fetchall() for row in rows: print(row) print("#" * 20) 

Удаление данных из таблицы

Напишем запрос на удаление. Говорим: Удалить запись из таблицы users, где id равен 1. У нас ведь пока только одна запись:

# delete data with connection.cursor() as cursor: delete_query = "DELETE FROM `users` WHERE cursor.execute(delete_query) connection.commit() 

Удаление таблицы

Последний запрос, который мы выполним. Давайте дропним нашу таблицу. Под словом дропнут подразумевается удаление всей таблицы целиком. Будьте аккуратны: данному запросу, как и запросу на создание таблицы, коммит не требуется:

# drop table with connection.cursor() as cursor: drop_table_query = "DROP TABLE `users`;" cursor.execute(drop_table_query) 

Полный код файла main.py:

import pymysql try: connection = pymysql.connect( host='127.0.0.1', port=3306, user='first_user', password='qwerty', database='db_name', cursorclass=pymysql.cursors.DictCursor ) print("successfully connected. ") print("#" * 20) try: # create table with connection.cursor() as cursor: create_table_query = "CREATE TABLE `users`(id int AUTO_INCREMENT," \ " name varchar(32)," \ " password varchar(32)," \ " email varchar(32), PRIMARY KEY (id));" cursor.execute(create_table_query) print("Table created successfully") insert data with connection.cursor() as cursor: insert_query = "INSERT INTO `users` (name, password, email) VALUES ('Anna', 'qwerty', 'anna@gmail.com');" cursor.execute(insert_query) connection.commit() # delete data with connection.cursor() as cursor: delete_query = "DELETE FROM `users` WHERE cursor.execute(delete_query) connection.commit() # drop table with connection.cursor() as cursor: drop_table_query = "DROP TABLE `users`;" cursor.execute(drop_table_query) # select all data from table with connection.cursor() as cursor: select_all_rows = "SELECT * FROM `users`" cursor.execute(select_all_rows) rows = cursor.fetchall() for row in rows: print(row) print("#" * 20) finally: connection.close() except Exception as ex: print("Connection refused. ") print(ex) 

Подведение итогов

Теперь вы знаете как можно подключаться к СУБД MySQL с помощью Python, а также выполнять любые запросы, включая создание таблиц, занесение в них данных, а также удаление строк и самих таблиц.

Надеюсь, статья вам помогла и вы узнали что-то новое. 👍

Материалы по теме

Источник

Читайте также:  Шаблон html для rust
Оцените статью