Mysql and python on windows

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

MySQL database connector for Python (with Python 3 support)

License

PyMySQL/mysqlclient

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This project is a fork of MySQLdb1. This project adds Python 3 support and fixed many bugs.

Do Not use Github Issue Tracker to ask help. OSS Maintainer is not free tech support

When your question looks relating to Python rather than MySQL:

Or when you have question about MySQL:

Building mysqlclient on Windows is very hard. But there are some binary wheels you can install easily.

If binary wheels do not exist for your version of Python, it may be possible to build from source, but if this does not work, do not come asking for support. To build from source, download the MariaDB C Connector and install it. It must be installed in the default location (usually «C:\Program Files\MariaDB\MariaDB Connector C» or «C:\Program Files (x86)\MariaDB\MariaDB Connector C» for 32-bit). If you build the connector yourself or install it in a different location, set the environment variable MYSQLCLIENT_CONNECTOR before installing. Once you have the connector installed and an appropriate version of Visual Studio for your version of Python:

Читайте также:  Html color chart numbers

Install MySQL and mysqlclient:

# Assume you are activating Python 3 venv $ brew install mysql pkg-config $ pip install mysqlclient 

If you don’t want to install MySQL server, you can use mysql-client instead:

# Assume you are activating Python 3 venv $ brew install mysql-client pkg-config $ export PKG_CONFIG_PATH="/opt/homebrew/opt/mysql-client/lib/pkgconfig" $ pip install mysqlclient 

Note that this is a basic step. I can not support complete step for build for all environment. If you can see some error, you should fix it by yourself, or ask for support in some user forum. Don’t file a issue on the issue tracker.

You may need to install the Python 3 and MySQL development headers and libraries like so:

  • $ sudo apt-get install python3-dev default-libmysqlclient-dev build-essential pkg-config # Debian / Ubuntu
  • % sudo yum install python3-devel mysql-devel pkgconfig # Red Hat / CentOS

Then you can install mysqlclient via pip now:

mysqlclient uses pkg-config —cflags —ldflags mysqlclient by default for finding compiler/linker flags.

You can use MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS environment variables to customize compiler/linker options.

$ export MYSQLCLIENT_CFLAGS=`pkg-config mysqlclient --cflags` $ export MYSQLCLIENT_LDFLAGS=`pkg-config mysqlclient --libs` $ pip install mysqlclient 

Documentation is hosted on Read The Docs

Источник

Mysql and python on windows

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

Создадим файл 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 и пишем запрос.

Читайте также:  Машинное зрение python opencv

Создать таблицу 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, а также выполнять любые запросы, включая создание таблиц, занесение в них данных, а также удаление строк и самих таблиц.

Читайте также:  Animation on display block css

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

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

Источник

Оцените статью