Python mysql database example

2. MySQL with Python¶

The ‘mysql-connector’ is not supported by Django-framework. The good option is ‘mysqlclient’ which is supported by Django as well.

$ mysql -u root -p Enter password: mysql> CREATE DATABASE pythonSQL; 

2.2. Connect and load data¶

Following code can be used to connect and load the data to database. Note that, the commands in the c.execute(…) statements are exactly same as the commands in the previous chapters.

# create_fill_database.py import mysql.connector as mc # connect to database conn= mc.connect(host='localhost',user='root',password='d',db='pythonSQL') c = conn.cursor() # cursor to perform operations def create_table(): """ Create table in the database """ # optional: drop table if exists c.execute('DROP TABLE IF EXISTS writer') c.execute('CREATE TABLE writer \ ( \ id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, \ name VARCHAR(30) NOT NULL UNIQUE, \ age int \ )' ) def insert_data(): """ Insert data to the table """ c.execute("INSERT INTO writer (name) VALUES ('Pearl Buck')") c.execute(" INSERT INTO writer VALUES \ (NULL, 'Rabindranath Tagore', 80), \ (NULL, 'Leo Tolstoy', 82)" \ ) c.execute(" INSERT INTO writer (age, name) VALUES \ (30, 'Meher Krishna Patel')" \ ) def commit_close(): """ commit changes to database and close connection """ conn.commit() c.close() conn.close() def main(): """ execute create and insert commands """ create_table() insert_data() commit_close() # required for save the changes # standard boilerplate to call main function if __name__ == '__main__': main() 
$ python create_fill_database.py

2.3. Read data from table¶

Following code can be used to read data from the table,

# read_database.py import mysql.connector as mc conn= mc.connect(host='localhost',user='root',password='d',db='pythonSQL') c = conn.cursor() def read_data(): c.execute('SELECT * FROM writer') writers = c.fetchall() # data is read in the form of list for writer in writers: # print individual item in the list print(writer) # data at each row is saved as tuple def main(): read_data() if __name__ == '__main__': main() 
$ python read_database.py (1, 'Pearl Buck', None) (2, 'Rabindranath Tagore', 80) (3, 'Leo Tolstoy', 82) (4, 'Meher Krishna Patel', 30) 
  • In this way, we can get the data from the table and perform various operations on the data.
  • Also, we can use all those queries with python, as queries in the execute statements are same as queries in previous chapter.
Читайте также:  Laravel php version requirements

2.4. Connection in try-except block¶

We can use following code to put the connection string in the try except block, so that we can get proper message for not connecting with the database,

# connect_try.py import mysql.connector as mq from mysql.connector import errorcode try: conn = mq.connect(host='localhost', user='root', password='d', db='pythonSQL') print("Connected") except mq.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") else: print(err) else: print("Connection closed") conn.close() 
$ python connect_try.py Connected Connection closed
$ python connect_try.py Something is wrong with your user name or password
$ python connect_try.py Database does not exist

© Copyright 2017, Meher Krishna Patel. Revision 31d452b4 .

Versions latest Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

Python mysql database example

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

Создадим файл 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 http post method

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

Читайте также:  How to add links in html

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

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

Источник

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