Pymysql

Introduction to MySQL Python connector

To access the MySQL database from Python, you need a database driver. MySQL Connector/Python is a standardized database driver provided by MySQL.

MySQL Connector/Python supports almost all features provided by MySQL version 5.7. It allows you to convert the parameter’s value between Python and MySQL data types e.g., Python datetime and MySQL .

MySQL Connector/Python is designed specifically to MySQL. It supports all MySQL extensions such as  clause.

MySQL Connector/Python allows you to compress the data stream between Python and MySQL database server using protocol compression. It supports connections using TCP/IP socket and secure TCP/IP connection using SSL.

MySQL Connector/Python is an API implemented using pure Python. It means that you don’t need to install any MySQL client library or any Python modules except the standard library.

Prevent SQL Injection

It is considered a good practice to escape the values of any query, also in
update statements.

This is to prevent SQL injections, which is a common web hacking technique to
destroy or misuse your database.

The mysql.connector module uses the placeholder to escape values in the delete statement:

Example

Escape values by using the placholder
method:

import mysql.connectormydb = mysql.connector.connect(  host=»localhost», 
user=»yourusername»,  password=»yourpassword»,  database=»mydatabase»)mycursor = mydb.cursor()sql = «UPDATE customers SET address = %s
WHERE address = %s»val = («Valley 345», «Canyon 123»)mycursor.execute(sql,
val)mydb.commit()print(mycursor.rowcount, «record(s)
affected»)

Способы выборки из таблиц

Объект cursor модуля MySQLdb поддерживает итерации. Это значит, что можно обойти все записи в наборе данных полученных из cur.execute без использования метода cur.fetchall, а просто используя инструкцию for row in cur:

Так же за место цикла for можно использовать цикл while

Обращение к данным по ключам может показаться неудобным, особенно если вы работает с большим набором данных из большого числа столбцов. Намного привычнее обращаться к данным по именам полей. Для этого напишем небольшую функцию-генератор. Вообще лучше сесть и написать хорошую обёртку во круг всего этого модуля. Например, можно динамически создавать курсор или даже делать коннект к базе.

Функцию-генератор по «именовыванию» последовательности записей.

Использовать её можно следующим образом:

2.3. Primary Key

Primary Key:- It is a unique value in the table. It helps to find each row uniquely in the table.

To create a Primary Key, we use the PRIMARY KEY statement while creating the table.

The statement INT AUTO_INCREMENT PRIMARY KEY is used to identify each row uniquely with a number starting from 1.

Let’s see how to create Primary Key for a table.

To see the table run the following code.

Dropping Primary Key

We use ALTER TABLE table_name DROP column_name statement to drop the column with Primary Key.

Now, we have dropped the Primary Key column. Let’s see how we can add a column with Primary Key to the existing table.

Adding Primary Key

Adding Primary Key to the existing table. We use ALTER TABLE table_name ADD PRIMARY KEY(column_name) statement to add a Primary Key to a table.

We have added the column id to the users table.

Install MySQL Connector Python on Ubuntu

Use the following command to install MySQL connector Python on Ubuntu.

sudo apt-get install mysql-connector-python

After this run the following command.

pip install mysql-connector-python

You can replace pip with pip3 if the command fails in Python3. If the above approach doesn’t work, you can still install it on Ubuntu using the source code.

  • Go to download MySQL Connector python for Ubuntu from here.
  • Select the Operating system Ubuntu Linux from the drop-down.
  • Select the OS version as an architecture-independent. I am selecting Ubuntu-Linux 16.04 (architecture-independent).
  •  You should get two entries fro DEB Package python for MySQL Connector Python (For python 2 and Python 3).
  • Download the listed DEB package and install it using the following commands.
  • First, unpack the DEB file and then install it.
    sudo dpkg -i /path_to_downloaded_deb_file

    After this run the following command.

    sudo apt-get install -f
  • You are now done with installing MySQL Connector Python on Ubuntu.

Table Of Contents

  1. 2.1.
    2.2. 2.3.
     

Note:

This tutorial is not meant to teach you complete SQL syntax or language.

This tutorial will teach you how you can work with MySQL in Python.

Procedure To Follow In Python To Work With MySQL

  1. Connect to the database.
     
  2. Create an object for your database.
     
  3. Execute the SQL query.
     
  4. Fetch records from the result.
     
  5. Informing the Database if you make any changes in the table.

1. Installing MySQL

MySQL is one of the most popular databases.

Download and install MySQL from the MySQL’s official website. You need to install the MySQL server to follow this tutorial.

Next, you have to install mysql.connector for Python. We need mysql.connector to connect Python Script to the MySQL database. Download the mysql.connector from here and install it on your computer.

Now, check whether you have installed the mysql.connector correctly or not using the following code.

If the above code runs without any errors, then you have successfully installed mysql.connector, and it is ready to use.

Курсор

Что бы выполнить какие-то операции в базе данных, сначала требуется создать объект соединения con, а затем вызвать метод con.cursor() создав курсор. Методы и свойства экземпляра cur класса Cursor используются для выполнения запросов к базе данных.

  • cur.close() – закрывает курсор предотвращая выполнения каких либо запросов с его помощью.
  • cur.callproc(procname ) – вызывает хранимую процедуру.
  • cur.execute(query ) – выполняет запрос к базе данных (query).
  • cur.executemany(query ) – многократное выполнение запросов к базе данных (query).
  • cur.fetchone() – возвращает следующую запись из набора данных полученого вызовом cur.execute*()
  • cur.fetchmany() – возвращает последовательность записей из набора данных.
  • cur.fetchall() – возвращает последовательность всех записей оставшихся в полученном наборе данных.
  • cur.nextset() – пропускает все оставшиеся записи в текущем наборе данных и переходит к следующему набору.
  • cur.setinputsize(sizes) – сообщает курсору о параметрах, которые будут переданы в последующих вызовах методов cur.execute*()
  • cur.setoutputsize(sizes ) – устанавливает размер буфера для определённого столбца в возвращаемом наборе данных.
  • cur.description — возвращает последовательность кортежей с информацией о каждом столбце в текущем наборе данных. Кортеж имеет вид (name, type_code, display_size, internal_size, precision, scale, null_ok)
  • cur.arraysize – целое число которое используется методом cur.fetchmany как значение по умолчанию.
  • cur.rowcount — возвратите число строк, на которые повлиял последний запрос.

DB API 2.0 Drivers

MySQL for Python

URL
License
GNU General Public License (GPL), Python License (CNRI Python License), Zope Public License
Platforms
OS Independent
Python versions
2.3 — 2.6
PyPI

MySQL on-line documentation, additional forums (maintainer does not currently read these)

mysqlclient

URL
License
GPL
Platforms
OS Independent
Python versions
Python 2.7 and 3.4+
PyPI

mysqlclient is a fork of MySQL-python. It adds Python 3 support and fixed many bugs. It is the MySQL library that is recommended by the Django documentation.

PyMySQL

URL
License
MIT
Platforms

OS Independent, CPython 2.x and 3.x, PyPy, Jython, IronPython

Python versions
2.4 — 3.2
PyPI
  • Pure-Python focused on simplicity and compatibility
  • Virtually 100% compatible with MySQLdb
  • Good performance

mxODBC

URL
License
eGenix Commercial License
Platforms
Windows, Linux, MacOS X, FreeBSD, Solaris, AIX
Python versions
2.4 — 2.7
PyPI

mxODBC is compatible with the MySQL ODBC driver on Windows and Unix.

pyodbc

URL
License
MIT
Platforms
Windows, Linux, MacOS X, FreeBSD, Solaris, Any (source provided)
Python versions
2.4+
PyPI

Actively maintained Open Source project.

Precompiled binaries are available for Windows. Red Hat Enterprise Linux, Centos, and Fedora have precompiled RPMs available in their Extras repositories.

MySQL Connector/Python

URL
License

GNU GPL v2 with FOSS License Exception

Platforms
Any (presumably)
Python versions

v2.6, v2.7 and Python v3.1 to 3.3 (See version overview)

PyPI
??
  • Implements the Python DB API 2.0 (PEP 249).
  • Pure Python implementation of the MySQL protocol.
  • Actively developed and maintained by Oracle.
  • Includes Django database backend.

mypysql

URL
License
GNU GPL v3+
Platforms
Any (presumably)
Python versions
3
PyPI
??
  • This module provides (yet) incomplete PEP 249 functionality
  • C implementation of MySQL database connector
  • A majority of the commands are implemented
  • Still experimental but actively developed

PyPyODBC (Pure Python ODBC)

URL
License
MIT
Platforms
Windows, Linux
Python versions
2.4 — 3.3
PyPI

One pure Python script, runs on CPython / IronPython / PyPy , Version 3.3 / 3.2 / 3.1 / 2.4 / 2.5 / 2.6 / 2.7 , Win / Linux , 32 / 64 bit.

Similar usage as pyodbc ( can be seen as a re-implementation of pyodbc in pure Python ).

Simple — the whole module is implemented in a single python script with less than 3000 lines.

mxODBC Connect

URL
License
eGenix Commercial License 1.3.0
Platforms
Client: all Python platforms; Server: Windows, Linux
Python versions
2.5 — 2.7
PyPI

mxODBC Connect is a commercial client-server product that allows connecting Python to ODBC compatible databases running on remote servers without requiring an ODBC driver on the client side. The product uses mxODBC on the server side and provides a highly portable Python library for the client side. As such it supports all database backend that mxODBC supports, but allows connecting to these from many different Python-supported platforms.

mxODBC Connect supports asynchronous query execution via the popular gevent package, provides secure certificate based authentication, SSL encrypted database connections, comes with full support for stored procedures, multiple result sets, Unicode, a common interface on all platforms and implements .

mxODBC Connect Server is compatible with the MySQL ODBC drivers.

Applications

  • Introduction into the sys module
  • Python and the Shell
  • Forks and Forking in Python
  • Introduction into Threads
  • Pipe, Pipes and «99 Bottles of Beer»
  • Python Network Scanner
  • Graph Theory and Graphs in Python
  • Graphs: PyGraph
  • Graphs
  • A Python Class for Polynomial Functions
  • Finite State Machine in Python
  • Turing Machine in Python
  • Levenshtein Distance
  • Verbalize Time in Turkish
  • Example for recursive Programming: Towers of Hanoi
  • Mastermind / Bulls and Cows
  • Creating dynamic websites with WSGI
  • Dynamic websites with mod_python
  • Dynamic websites with Pylons
  • Python, SQL, MySQL and SQLite
  • Python Scores

Help Needed


«You can have data without information, but you cannot have information without data.»
(Daniel Keys Moran)
Python Training Courses in Toronto, Canada
«Database Management System A complex set of interrelational data structures allowing data to be lost in
many convenient sequences while retaining a complete record of the logical relations between
the missing items.»
From The Devil’s DP Dictionary»
by Stan Kelly-Bootle
»

Download and Install MySQL Connector Python on MacOs

You can Installing MySQL Connector Python on macOS Using a Disk Image.

  • Go to download MySQL Connector python for macOS from here
  • Refer the above table to check which version is compatible with your python version
  • Download the mysql-connector-python-8.0.11-macos10.13.dmg file. it is an architecture Independent DMG file.
  • .Install the downloaded MySQL Connector Python by opening it and double-clicking the resulting .pkg file.

Verifying MySQL Connector Python installation on macOS

Check that MySQL Connector Python installation is working and able to connect to MySQL Server by Connecting to MySQL Using MySQL Connector Python.

Fortgeschrittene

  • Einführung in das sys-Modul
  • Python und die Shell
  • Forks und Forking in Python
  • Einführung in Threads
  • Pipe, Pipes und «99 Bottles of Beer»
  • Graphen in Python
  • Ein Beispiel für Rekursion: Türme von Hanoi
  • Endlicher Automat
  • Turingmaschine
  • Arbeiten mit XML und SAX
  • Python und SQL
  • Musik komponieren mit Python
  • Einführung in die Text-Klassifikation
  • Text-Klassifikation in Python

Spenden


«You can have data without information, but you cannot have information without data.»
(Deutsche Übersetzung: Man kann Daten ohne Informationen haben, aber man kann keine Informationen ohne Daten haben.)
(Daniel Keys Moran)

«Database Management System A complex set of interrelational data structures allowing data to be lost in
many convenient sequences while retaining a complete record of the logical relations between
the missing items.»
From The Devil’s DP Dictionary»
by Stan Kelly-Bootle
»

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *