Giter Site home page Giter Site logo

pymysql / mysqlclient Goto Github PK

View Code? Open in Web Editor NEW
2.4K 2.4K 433.0 1.82 MB

MySQL/MariaDB connector for Python

Home Page: https://mysqlclient.readthedocs.io/

License: GNU General Public License v2.0

Python 64.30% C 35.58% Makefile 0.12%
mariadb mysql python

mysqlclient's Introduction

Documentation Status codecov

PyMySQL

This package contains a pure-Python MySQL client library, based on PEP 249.

Requirements

  • Python -- one of the following:
  • MySQL Server -- one of the following:

Installation

Package is uploaded on PyPI.

You can install it with pip:

$ python3 -m pip install PyMySQL

To use "sha256_password" or "caching_sha2_password" for authenticate, you need to install additional dependency:

$ python3 -m pip install PyMySQL[rsa]

To use MariaDB's "ed25519" authentication method, you need to install additional dependency:

$ python3 -m pip install PyMySQL[ed25519]

Documentation

Documentation is available online: https://pymysql.readthedocs.io/

For support, please refer to the StackOverflow.

Example

The following examples make use of a simple table

CREATE TABLE `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `email` varchar(255) COLLATE utf8_bin NOT NULL,
    `password` varchar(255) COLLATE utf8_bin NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
AUTO_INCREMENT=1 ;
import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             database='db',
                             cursorclass=pymysql.cursors.DictCursor)

with connection:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('[email protected]', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('[email protected]',))
        result = cursor.fetchone()
        print(result)

This example will print:

{'password': 'very-secret', 'id': 1}

Resources

License

PyMySQL is released under the MIT License. See LICENSE for more information.

mysqlclient's People

Contributors

adamchainz avatar benjaminp avatar carsonip avatar djailla avatar emonty avatar evax avatar farcepest avatar frewsxcv avatar fried avatar gbandet avatar graingert avatar hamarituc avatar jeansch avatar jnozsc avatar methane avatar msabramo avatar mschoettle avatar nestortejero avatar okin avatar phispi avatar ravyn440 avatar renovate[bot] avatar scop avatar sir-sigurd avatar supervirus avatar timgates42 avatar tiwilliam avatar tyzhnenko avatar vtermanis avatar zxymike93 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mysqlclient's Issues

'surrogates not allowed' error on stored procedure call for unicode argument

On python 3.5.1, mysqlclient 1.3.7

cursor.callproc() with unicode string argument generates error below
'utf-8' codec can't encode character '\udceb' in position 39: surrogates not allowed

The code works if I change below code

def literal(self, o): 
    s = self.escape(o, self.encoders)
    if not PY2 and isinstance(s, bytes):
        return s.decode('ascii', 'surrogateescape')
    return s

to

def literal(self, o): 
    s = self.escape(o, self.encoders)
    if not PY2 and isinstance(s, bytes):
        return s.decode('utf8', 'surrogateescape')
    return s

changes : 'ascii' to 'utf8'
ps. tested string was korean string, "제권".

escape_string() broken with Python 2.x

$ python -c 'import MySQLdb; print(MySQLdb.escape_string(b"foo"))'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: must be impossible<bad format char>, not str
$ python3 -c 'import MySQLdb; print(MySQLdb.escape_string(b"foo"))'
b'foo'

Tested on Debian with version 1.3.4-1 (packaged in experimental), MariaDB 10.0.16-1 and Python 2.7.9-1
I also tried 1.3.5 but it's not better.

Wheel for Windows?

I see that version 1.3.4 had wheels for Windows, and I was wondering whether you could also put up wheels for the newest version? It would make it much easier to recommend using this package.

License Offerings

Hello! Recently, I started working through building my own Python 3 support for MySQLdb. However, before I started doing so I had come across a post by the original author, @farcepest on Sourceforge about how users could optionally use the CNRI license (I've copied the post here in case it disappears for some reason).

I think given your work on MySQLdb, and given that @farcepest originally offered it, I think it would be really cool if you would extend that offer onto the users of mysqlclient-python.

In @farcepest's post, he mentions that this CNRI offering applies to versions of MySQLdb lower than 1.3, (mysqlclient-python forked MySQLdb at version 1.2).

The gist of the offering would be allowing the users to choose either the CNRI license, or GPL2. That said though that could get a little confusing, but is a really nice choice I think.

Do you have any thoughts on the issue?

Add "_binary" prefix when converting binary data

Since 5.6.27, mysql server produces a warning if string literals cannot
be interpreted in a given character set (See bug #20238729 at MySQL)
It seems like the "_binary" prefix is the best way to prevent MySQL server from treating a binary data as utf-8 (or other connection charset) characters.
Already done at PyMySQL

Error pip install MySQL-python [ i am using Python 3.5 in windows 10 ]

Error message :

(myenv) E:\py-test>pip install MySQL-python
Collecting MySQL-python
Using cached MySQL-python-1.2.5.zip
Building wheels for collected packages: MySQL-python
Running setup.py bdist_wheel for MySQL-python ... error
Complete output from command e:\py-test\myenv\scripts\python.exe -u -c "import setuptools, tokenize;file='C:\Users\ALGOBA1\AppData\Local\Temp\pip-build-i0p6rlub\MySQL-python\setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" bdist_wheel -d C:\Users\ALGOBA1\AppData\Local\Temp\tmp7hy7_45apip-wheel- --python-tag cp35:
running bdist_wheel
running build
running build_py
creating build
creating build\lib.win32-3.5
copying mysql_exceptions.py -> build\lib.win32-3.5
creating build\lib.win32-3.5\MySQLdb
copying MySQLdb__init
_.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\converters.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\connections.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\release.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\times.py -> build\lib.win32-3.5\MySQLdb
creating build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants__init__.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.5\MySQLdb\constants
running build_ext
building '_mysql' extension
error: Unable to find vcvarsall.bat


Failed building wheel for MySQL-python
Running setup.py clean for MySQL-python
Failed to build MySQL-python
Installing collected packages: MySQL-python
Running setup.py install for MySQL-python ... error
Complete output from command e:\py-test\myenv\scripts\python.exe -u -c "import setuptools, tokenize;file='C:\Users\ALGOBA1\AppData\Local\Temp\pip-build-i0p6rlub\MySQL-python\setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record C:\Users\ALGOBA1\AppData\Local\Temp\pip-xires3pm-record\install-record.txt --single-version-externally-managed --compile --install-headers e:\py-test\myenv\include\site\python3.5\MySQL-python:
running install
running build
running build_py
creating build
creating build\lib.win32-3.5
copying mysql_exceptions.py -> build\lib.win32-3.5
creating build\lib.win32-3.5\MySQLdb
copying MySQLdb__init
_.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\converters.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\connections.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\release.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\times.py -> build\lib.win32-3.5\MySQLdb
creating build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants__init__.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.5\MySQLdb\constants
running build_ext
building '_mysql' extension
error: Unable to find vcvarsall.bat

Change the import name from MySQLdb to mysqlclient to avoid conflicts, or taking over "MySQL-python" on PyPI

It is destabilizing to expect that a particular application that wishes to make use of "mysqlclient" under Python 2K must therefore in one step use mysqlclient for all applications that share the same virtual or actual Python environment. it should be be possible for some applications to use the traditional MySQLdb and for others to use mysqlclient.

Other DBAPIs that began as forks or ports of others have followed this practice, e.g. fdb is a port of kinterbasdb, psycopg2cffi is a pypy port of psycopg2, etc. It only creates confusion and reduces options when two totally different codebases share the exact same module name. Especially on Linux distributions it means that two packages will necessarily overwrite each other and be in conflict.

async write to connection

I as far as I can see only read from connection is async? What about write operation? For instance we have very slow network, so internal buffer cleared very slowly, connection will be blocked? Is is possible to yield control back to loop in such situation?

Failed building wheel for mysqlclient

I'm using Python 3.5.1 and pip 8.0.2 on OS X that I installed using pyenv. When installing mysqlclient I get the error "Failed building wheel for mysqlclient". The following is my terminal output.

$ pip install mysqlclient==1.3.7
Collecting mysqlclient==1.3.7
  Using cached mysqlclient-1.3.7.tar.gz
Building wheels for collected packages: mysqlclient
  Running setup.py bdist_wheel for mysqlclient ... error
  Complete output from command /Users/brento/.virtualenvs/pears-py3/bin/python3.5 -u -c "import setuptools, tokenize;__file__='/private/var/folders/q8/nr7dx6213ld0p451xxqm138h0000gp/T/pip-build-rayxd4we/mysqlclient/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /var/folders/q8/nr7dx6213ld0p451xxqm138h0000gp/T/tmpvg5zyj7upip-wheel- --python-tag cp35:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.macosx-10.11-x86_64-3.5
  copying _mysql_exceptions.py -> build/lib.macosx-10.11-x86_64-3.5
  creating build/lib.macosx-10.11-x86_64-3.5/MySQLdb
  copying MySQLdb/__init__.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb
  copying MySQLdb/compat.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb
  copying MySQLdb/converters.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb
  copying MySQLdb/connections.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb
  copying MySQLdb/cursors.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb
  copying MySQLdb/release.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb
  copying MySQLdb/times.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb
  creating build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants
  copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants
  copying MySQLdb/constants/CR.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants
  copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants
  copying MySQLdb/constants/ER.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants
  copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants
  copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants
  copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants
  running build_ext
  building '_mysql' extension
  creating build/temp.macosx-10.11-x86_64-3.5
  clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -Dversion_info=(1,3,7,'final',1) -D__version__=1.3.7 -I/usr/local/Cellar/mysql/5.7.10/include/mysql -I/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/include/python3.5m -c _mysql.c -o build/temp.macosx-10.11-x86_64-3.5/_mysql.o -fno-omit-frame-pointer
  clang -bundle -undefined dynamic_lookup -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk build/temp.macosx-10.11-x86_64-3.5/_mysql.o -L/usr/local/Cellar/mysql/5.7.10/lib -lmysqlclient -lssl -lcrypto -o build/lib.macosx-10.11-x86_64-3.5/_mysql.cpython-35m-darwin.so
  installing to build/bdist.macosx-10.11-x86_64/wheel
  running install
  running install_lib
  creating build/bdist.macosx-10.11-x86_64
  creating build/bdist.macosx-10.11-x86_64/wheel
  copying build/lib.macosx-10.11-x86_64-3.5/_mysql.cpython-35m-darwin.so -> build/bdist.macosx-10.11-x86_64/wheel
  copying build/lib.macosx-10.11-x86_64-3.5/_mysql_exceptions.py -> build/bdist.macosx-10.11-x86_64/wheel
  creating build/bdist.macosx-10.11-x86_64/wheel/MySQLdb
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/__init__.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/compat.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/connections.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb
  creating build/bdist.macosx-10.11-x86_64/wheel/MySQLdb/constants
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants/__init__.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb/constants
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants/CLIENT.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb/constants
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants/CR.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb/constants
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants/ER.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb/constants
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants/FIELD_TYPE.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb/constants
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants/FLAG.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb/constants
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/constants/REFRESH.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb/constants
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/converters.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/cursors.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/release.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb
  copying build/lib.macosx-10.11-x86_64-3.5/MySQLdb/times.py -> build/bdist.macosx-10.11-x86_64/wheel/MySQLdb
  running install_egg_info
  running egg_info
  writing top-level names to mysqlclient.egg-info/top_level.txt
  writing dependency_links to mysqlclient.egg-info/dependency_links.txt
  writing mysqlclient.egg-info/PKG-INFO
  warning: manifest_maker: standard file '-c' not found

  reading manifest file 'mysqlclient.egg-info/SOURCES.txt'
  reading manifest template 'MANIFEST.in'
  writing manifest file 'mysqlclient.egg-info/SOURCES.txt'
  Copying mysqlclient.egg-info to build/bdist.macosx-10.11-x86_64/wheel/mysqlclient-1.3.7-py3.5.egg-info
  running install_scripts
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "/private/var/folders/q8/nr7dx6213ld0p451xxqm138h0000gp/T/pip-build-rayxd4we/mysqlclient/setup.py", line 21, in <module>
      setuptools.setup(**metadata)
    File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/distutils/core.py", line 148, in setup
      dist.run_commands()
    File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/distutils/dist.py", line 955, in run_commands
      self.run_command(cmd)
    File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/distutils/dist.py", line 974, in run_command
      cmd_obj.run()
    File "/Users/brento/.virtualenvs/pears-py3/lib/python3.5/site-packages/wheel/bdist_wheel.py", line 213, in run
      archive_basename = self.get_archive_basename()
    File "/Users/brento/.virtualenvs/pears-py3/lib/python3.5/site-packages/wheel/bdist_wheel.py", line 161, in get_archive_basename
      impl_tag, abi_tag, plat_tag = self.get_tag()
    File "/Users/brento/.virtualenvs/pears-py3/lib/python3.5/site-packages/wheel/bdist_wheel.py", line 155, in get_tag
      assert tag == supported_tags[0]
  AssertionError

  ----------------------------------------
  Failed building wheel for mysqlclient
  Running setup.py clean for mysqlclient
Failed to build mysqlclient
Installing collected packages: mysqlclient
  Found existing installation: mysqlclient 1.3.6
    Uninstalling mysqlclient-1.3.6:
      Successfully uninstalled mysqlclient-1.3.6
  Running setup.py install for mysqlclient ... done
Successfully installed mysqlclient-1.3.7

Mysqlclient stopped working when Mysql was upgraded to 5.7.9

Maybe this can not be considered a issue, sorry about it

Mysqlclient worked with Mysql Server 5.5 in Ubuntu 14.04, but recently I upgraded to Mysql Community server 5.7.9 and now when I try import it I get:

ImportError: libmysqlclient.so.18: cannot open shared object file: No such file or directory

Well, after the upgrade, libmysqclient.so.20 exists rather than libmysqclient.so.18 so I tried to modify LD_LIBRARY_PATH to add the new path to libmysqclient.so.20 i.e. http://stackoverflow.com/questions/511011/how-can-i-tell-python-which-version-of-libmysqlclient-so-to-use

The problem persists with the same message, so I tried to reinstall mysqlclient from source code and I get the following:

running install
running bdist_egg
running egg_info
writing mysqlclient.egg-info/PKG-INFO
writing top-level names to mysqlclient.egg-info/top_level.txt
writing dependency_links to mysqlclient.egg-info/dependency_links.txt
reading manifest file 'mysqlclient.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'mysqlclient.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
copying MySQLdb/release.py -> build/lib.linux-x86_64-3.4/MySQLdb
running build_ext
building '_mysql' extension
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,3,7,'final',1) -D__version__=1.3.7 -I/usr/include/mysql -I/usr/include/python3.4m -I/home/yoelzalas/tornado/include/python3.4m -c _mysql.c -o build/temp.linux-x86_64-3.4/_mysql.o -fabi-version=2 -fno-omit-frame-pointer
In file included from /usr/include/mysql/mysql.h:64:0,
                 from _mysql.c:30:
/usr/include/mysql/mysql/client_plugin.h:97:3: warning: function declaration isn’t a prototype [-Wstrict-prototypes]
   MYSQL_CLIENT_PLUGIN_HEADER
   ^
In file included from /usr/include/mysql/mysql.h:64:0,
                 from _mysql.c:30:
/usr/include/mysql/mysql/client_plugin.h:107:3: warning: function declaration isn’t a prototype [-Wstrict-prototypes]
   MYSQL_CLIENT_PLUGIN_HEADER
   ^
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.4/_mysql.o -L/usr/lib/x86_64-linux-gnu -lmysqlclient -lpthread -lz -lm -lrt -ldl -o build/lib.linux-x86_64-3.4/_mysql.cpython-34m.so
/usr/bin/ld: no se puede encontrar -lz
collect2: error: ld returned 1 exit status
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

Is this a incompatibility of mysql version?

Warning handling broken with multi-statements

If you use connection.set_server_option(MYSQL_OPTION_MULTI_STATEMENTS_ON) and then send a pair of queries which both cause warnings, MySQLdb breaks when checking for the warnings.

In [1]: import MySQLdb

In [2]: conn = MySQLdb.connect(db='test')

In [3]: conn.set_server_option(0)  # multi statements on
Out[3]: 0

In [4]: cur = conn.cursor()

In [5]: cur.execute("drop table if exists atest; drop table if exists atest;")
---------------------------------------------------------------------------
ProgrammingError                          Traceback (most recent call last)
<ipython-input-5-62f3396e70c7> in <module>()
----> 1 cur.execute("drop table if exists atest; drop table if exists atest;")

/usr/local/lib/python2.7/site-packages/MySQLdb/cursors.pyc in execute(self, query, args)
    174             self.errorhandler(self, exc, value)
    175         self._executed = query
--> 176         if not self._defer_warnings: self._warning_check()
    177         return r
    178 

/usr/local/lib/python2.7/site-packages/MySQLdb/cursors.pyc in _warning_check(self)
     83         from warnings import warn
     84         if self._warnings:
---> 85             warnings = self._get_db().show_warnings()
     86             if warnings:
     87                 # This is done in two loops in case

/usr/local/lib/python2.7/site-packages/MySQLdb/connections.pyc in show_warnings(self)
    315         is an earlier version, an empty sequence is returned."""
    316         if self._server_version < (4,1): return ()
--> 317         self.query("SHOW WARNINGS")
    318         r = self.store_result()
    319         warnings = r.fetch_row(0)

ProgrammingError: (2014, "Commands out of sync; you can't run this command now")

New release to fix regression?

Hi, for the Django test suite we are currently pinned to an older version of mysqlclient due to a regression when using a cursor as a context manager (fixed by 641a2eb, I think). Would it be possible to get a new release soon? Thanks!

py3/unicode errors

running the sqlalchemy 0.9.9 testsuite with mysqlclient HEAD I got the following errors
(see https://bitbucket.org/zzzeek/sqlalchemy/issue/3358/py3k-support-for-mysqldb-via-mysqlclient#comment-17218449)

=================================== FAILURES ===================================
________________ TypesTest_mysql_mysqldb.test_bit_50_roundtrip _________________
Traceback (most recent call last):
  File "<string>", line 2, in test_bit_50_roundtrip
  File "$path/test/../lib/sqlalchemy/testing/exclusions.py", line 84, in decorate
    return self._do(config._current, fn, *args, **kw)
  File "$path/test/../lib/sqlalchemy/testing/exclusions.py", line 114, in _do
    self._expect_failure(config, ex, name=fn.__name__)
  File "$path/test/../lib/sqlalchemy/testing/exclusions.py", line 126, in _expect_failure
    util.raise_from_cause(ex)
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 188, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=exc_value)
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 182, in reraise
    raise value
  File "$path/test/../lib/sqlalchemy/testing/exclusions.py", line 112, in _do
    return_value = fn(*args, **kw)
  File "<string>", line 2, in test_bit_50_roundtrip
  File "$path/test/../lib/sqlalchemy/testing/util.py", line 191, in provide_metadata
    return fn(*args, **kw)
  File "$path/test/dialect/mysql/test_types.py", line 337, in test_bit_50_roundtrip
    roundtrip([0, 0, 0, 0, i, i, i, i])
  File "$path/test/dialect/mysql/test_types.py", line 321, in roundtrip
    row = table.select().execute().first()
  File "$path/test/../lib/sqlalchemy/sql/base.py", line 386, in execute
    return e._execute_clauseelement(self, multiparams, params)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1870, in _execute_clauseelement
    return connection._execute_clauseelement(elem, multiparams, params)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 938, in _execute_clauseelement
    compiled_sql, distilled_params
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1070, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1274, in _handle_dbapi_exception
    util.reraise(*exc_info)
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 182, in reraise
    raise value
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1063, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/default.py", line 442, in do_execute
    cursor.execute(statement, parameters)
  File "$site/MySQLdb/cursors.py", line 220, in execute
    self.errorhandler(self, exc, value)
  File "$site/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "$site/MySQLdb/cursors.py", line 209, in execute
    r = self._query(query)
  File "$site/MySQLdb/cursors.py", line 373, in _query
    self._post_get_result()
  File "$site/MySQLdb/cursors.py", line 377, in _post_get_result
    self._rows = self._fetch_row(0)
  File "$site/MySQLdb/cursors.py", line 345, in _fetch_row
    return self._result.fetch_row(size, self._fetch_type)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
__________________ CompiledCacheTest_mysql_mysqldb.test_cache __________________
Traceback (most recent call last):
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1063, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/default.py", line 442, in do_execute
    cursor.execute(statement, parameters)
  File "$site/MySQLdb/cursors.py", line 220, in execute
    self.errorhandler(self, exc, value)
  File "$site/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "$site/MySQLdb/cursors.py", line 209, in execute
    r = self._query(query)
  File "$site/MySQLdb/cursors.py", line 372, in _query
    rowcount = self._do_query(q)
  File "$site/MySQLdb/cursors.py", line 335, in _do_query
    db.query(q)
  File "$site/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (1054, "Unknown column 'user_name' in 'field list'")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "$path/test/engine/test_execute.py", line 730, in test_cache
    cached_conn.execute(ins, {'user_name': 'u1'})
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 841, in execute
    return meth(self, multiparams, params)
  File "$path/test/../lib/sqlalchemy/sql/elements.py", line 322, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 938, in _execute_clauseelement
    compiled_sql, distilled_params
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1070, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1271, in _handle_dbapi_exception
    exc_info
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 188, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=exc_value)
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 181, in reraise
    raise value.with_traceback(tb)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1063, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/default.py", line 442, in do_execute
    cursor.execute(statement, parameters)
  File "$site/MySQLdb/cursors.py", line 220, in execute
    self.errorhandler(self, exc, value)
  File "$site/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "$site/MySQLdb/cursors.py", line 209, in execute
    r = self._query(query)
  File "$site/MySQLdb/cursors.py", line 372, in _query
    rowcount = self._do_query(q)
  File "$site/MySQLdb/cursors.py", line 335, in _do_query
    db.query(q)
  File "$site/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
sqlalchemy.exc.OperationalError: (OperationalError) (1054, "Unknown column 'user_name' in 'field list'") b'INSERT INTO users (user_name) VALUES (%s)' ('u1',)
______ CompiledCacheTest_mysql_mysqldb.test_keys_independent_of_ordering _______
Traceback (most recent call last):
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1063, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/default.py", line 442, in do_execute
    cursor.execute(statement, parameters)
  File "$site/MySQLdb/cursors.py", line 220, in execute
    self.errorhandler(self, exc, value)
  File "$site/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "$site/MySQLdb/cursors.py", line 209, in execute
    r = self._query(query)
  File "$site/MySQLdb/cursors.py", line 372, in _query
    rowcount = self._do_query(q)
  File "$site/MySQLdb/cursors.py", line 335, in _do_query
    db.query(q)
  File "$site/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (1054, "Unknown column 'user_name' in 'field list'")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "$path/test/engine/test_execute.py", line 741, in test_keys_independent_of_ordering
    {"user_id": 1, "user_name": "u1", "extra_data": "e1"})
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 841, in execute
    return meth(self, multiparams, params)
  File "$path/test/../lib/sqlalchemy/sql/elements.py", line 322, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 938, in _execute_clauseelement
    compiled_sql, distilled_params
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1070, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1271, in _handle_dbapi_exception
    exc_info
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 188, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=exc_value)
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 181, in reraise
    raise value.with_traceback(tb)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1063, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/default.py", line 442, in do_execute
    cursor.execute(statement, parameters)
  File "$site/MySQLdb/cursors.py", line 220, in execute
    self.errorhandler(self, exc, value)
  File "$site/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "$site/MySQLdb/cursors.py", line 209, in execute
    r = self._query(query)
  File "$site/MySQLdb/cursors.py", line 372, in _query
    rowcount = self._do_query(q)
  File "$site/MySQLdb/cursors.py", line 335, in _do_query
    db.query(q)
  File "$site/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
sqlalchemy.exc.OperationalError: (OperationalError) (1054, "Unknown column 'user_name' in 'field list'") b'INSERT INTO users (user_id, user_name, extra_data) VALUES (%s, %s, %s)' (1, 'u1', 'e1')
_____ EngineEventsTest_mysql_mysqldb.test_cursor_events_ctx_execute_scalar _____
Traceback (most recent call last):
  File "$path/test/engine/test_execute.py", line 1197, in test_cursor_events_ctx_execute_scalar
    [call(conn, ctx.cursor, stmt, ctx.parameters[0], ctx, False)])
  File "$path/test/../lib/sqlalchemy/testing/assertions.py", line 187, in eq_
    assert a == b, msg or "%r != %r" % (a, b)
AssertionError: [call(<sqlalchemy.engine.base.Connection object at 0x1071d96a0>, <MySQLdb.cursors.Cursor object at 0x106bc29b0>, b'SELECT 1', (), <sqlalchemy.dialects.mysql.mysqldb.MySQLExecutionContext_mysqldb object at 0x106c25a90>, False)] != [call(<sqlalchemy.engine.base.Connection object at 0x1071d96a0>, <MySQLdb.cursors.Cursor object at 0x106bc29b0>, 'SELECT 1', (), <sqlalchemy.dialects.mysql.mysqldb.MySQLExecutionContext_mysqldb object at 0x106c25a90>, False)]
__________ EngineEventsTest_mysql_mysqldb.test_cursor_events_execute ___________
Traceback (most recent call last):
  File "$path/test/engine/test_execute.py", line 1216, in test_cursor_events_execute
    [call(conn, ctx.cursor, stmt, ctx.parameters[0], ctx, False)])
  File "$path/test/../lib/sqlalchemy/testing/assertions.py", line 187, in eq_
    assert a == b, msg or "%r != %r" % (a, b)
AssertionError: [call(<sqlalchemy.engine.base.Connection object at 0x1071fc048>, <MySQLdb.cursors.Cursor object at 0x10719dcc0>, b'SELECT 1', (), <sqlalchemy.dialects.mysql.mysqldb.MySQLExecutionContext_mysqldb object at 0x106c17710>, False)] != [call(<sqlalchemy.engine.base.Connection object at 0x1071fc048>, <MySQLdb.cursors.Cursor object at 0x10719dcc0>, 'SELECT 1', (), <sqlalchemy.dialects.mysql.mysqldb.MySQLExecutionContext_mysqldb object at 0x106c17710>, False)]
______________ EngineEventsTest_mysql_mysqldb.test_execute_events ______________
Traceback (most recent call last):
  File "<string>", line 2, in test_execute_events
  File "$path/test/../lib/sqlalchemy/testing/exclusions.py", line 84, in decorate
    return self._do(config._current, fn, *args, **kw)
  File "$path/test/../lib/sqlalchemy/testing/exclusions.py", line 114, in _do
    self._expect_failure(config, ex, name=fn.__name__)
  File "$path/test/../lib/sqlalchemy/testing/exclusions.py", line 126, in _expect_failure
    util.raise_from_cause(ex)
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 188, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=exc_value)
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 182, in reraise
    raise value
  File "$path/test/../lib/sqlalchemy/testing/exclusions.py", line 112, in _do
    return_value = fn(*args, **kw)
  File "$path/test/engine/test_execute.py", line 1313, in test_execute_events
    self._assert_stmts(cursor, cursor_stmts)
  File "$path/test/engine/test_execute.py", line 1079, in _assert_stmts
    assert False, "Nothing available for stmt: %s" % stmt
AssertionError: Nothing available for stmt: INSERT INTO t1 (c1, c2)
assert False
__________ ExecuteTest_mysql_mysqldb.test_unicode_test_fails_warning ___________
Traceback (most recent call last):
  File "$path/test/../lib/sqlalchemy/pool.py", line 951, in _do_get
    return self._pool.get(wait, self._timeout)
  File "$path/test/../lib/sqlalchemy/util/queue.py", line 145, in get
    raise Empty
sqlalchemy.util.queue.Empty

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "$path/test/engine/test_execute.py", line 522, in test_unicode_test_fails_warning
    eng.connect
  File "$path/test/../lib/sqlalchemy/testing/assertions.py", line 224, in assert_raises_message
    callable_(*args, **kwargs)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1890, in connect
    return self._connection_cls(self, **kwargs)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 60, in __init__
    self.__connection = connection or engine.raw_connection()
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1964, in raw_connection
    return self.pool.unique_connection()
  File "$path/test/../lib/sqlalchemy/pool.py", line 280, in unique_connection
    return _ConnectionFairy._checkout(self)
  File "$path/test/../lib/sqlalchemy/pool.py", line 645, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "$path/test/../lib/sqlalchemy/pool.py", line 440, in checkout
    rec = pool._do_get()
  File "$path/test/../lib/sqlalchemy/pool.py", line 964, in _do_get
    return self._create_connection()
  File "$path/test/../lib/sqlalchemy/pool.py", line 285, in _create_connection
    return _ConnectionRecord(self)
  File "$path/test/../lib/sqlalchemy/pool.py", line 416, in __init__
    exec_once(self.connection, self)
  File "$path/test/../lib/sqlalchemy/event/attr.py", line 250, in exec_once
    self(*args, **kw)
  File "$path/test/../lib/sqlalchemy/event/attr.py", line 260, in __call__
    fn(*args, **kw)
  File "$path/test/../lib/sqlalchemy/util/langhelpers.py", line 1219, in go
    return once_fn(*arg, **kw)
  File "$path/test/../lib/sqlalchemy/engine/strategies.py", line 166, in first_connect
    dialect.initialize(c)
  File "$path/test/../lib/sqlalchemy/dialects/mysql/base.py", line 2453, in initialize
    self._detect_ansiquotes(connection)
  File "$path/test/../lib/sqlalchemy/dialects/mysql/base.py", line 2718, in _detect_ansiquotes
    connection.execute("SHOW VARIABLES LIKE 'sql_mode'"),
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 833, in execute
    return self._execute_text(object, multiparams, params)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 982, in _execute_text
    statement, parameters
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1070, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1274, in _handle_dbapi_exception
    util.reraise(*exc_info)
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 182, in reraise
    raise value
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1063, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/default.py", line 442, in do_execute
    cursor.execute(statement, parameters)
  File "$path/test/engine/test_execute.py", line 514, in execute
    if "test unicode returns" in stmt:
TypeError: 'str' does not support the buffer interface
______ HandleErrorTest_mysql_mysqldb.test_exception_event_non_dbapi_error ______
Traceback (most recent call last):
  File "$path/test/engine/test_execute.py", line 1827, in test_exception_event_non_dbapi_error
    eq_(ctx.statement, "select ")
  File "$path/test/../lib/sqlalchemy/testing/assertions.py", line 187, in eq_
    assert a == b, msg or "%r != %r" % (a, b)
AssertionError: b'select ' != 'select '
----------------------------- Captured stdout call -----------------------------
b"I'm not a DBAPI error"
_______________ HandleErrorTest_mysql_mysqldb.test_handle_error ________________
Traceback (most recent call last):
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1063, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/default.py", line 442, in do_execute
    cursor.execute(statement, parameters)
  File "$site/MySQLdb/cursors.py", line 220, in execute
    self.errorhandler(self, exc, value)
  File "$site/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "$site/MySQLdb/cursors.py", line 209, in execute
    r = self._query(query)
  File "$site/MySQLdb/cursors.py", line 372, in _query
    rowcount = self._do_query(q)
  File "$site/MySQLdb/cursors.py", line 335, in _do_query
    db.query(q)
  File "$site/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
_mysql_exceptions.ProgrammingError: (1146, "Table 'test_schema.i_dont_exist' doesn't exist")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "$path/test/engine/test_execute.py", line 1638, in test_handle_error
    conn.execute("SELECT FOO FROM I_DONT_EXIST")
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 833, in execute
    return self._execute_text(object, multiparams, params)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 982, in _execute_text
    statement, parameters
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1070, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1271, in _handle_dbapi_exception
    exc_info
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 188, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=exc_value)
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 181, in reraise
    raise value.with_traceback(tb)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1063, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/default.py", line 442, in do_execute
    cursor.execute(statement, parameters)
  File "$site/MySQLdb/cursors.py", line 220, in execute
    self.errorhandler(self, exc, value)
  File "$site/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "$site/MySQLdb/cursors.py", line 209, in execute
    r = self._query(query)
  File "$site/MySQLdb/cursors.py", line 372, in _query
    rowcount = self._do_query(q)
  File "$site/MySQLdb/cursors.py", line 335, in _do_query
    db.query(q)
  File "$site/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
sqlalchemy.exc.ProgrammingError: (ProgrammingError) (1146, "Table 'test_schema.i_dont_exist' doesn't exist") b'SELECT FOO FROM I_DONT_EXIST' ()

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "$path/test/engine/test_execute.py", line 1645, in test_handle_error
    eq_(ctx.statement, "SELECT FOO FROM I_DONT_EXIST")
  File "$path/test/../lib/sqlalchemy/testing/assertions.py", line 187, in eq_
    assert a == b, msg or "%r != %r" % (a, b)
AssertionError: b'SELECT FOO FROM I_DONT_EXIST' != 'SELECT FOO FROM I_DONT_EXIST'
____________ HandleErrorTest_mysql_mysqldb.test_legacy_dbapi_error _____________
Traceback (most recent call last):
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1063, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/default.py", line 442, in do_execute
    cursor.execute(statement, parameters)
  File "$site/MySQLdb/cursors.py", line 220, in execute
    self.errorhandler(self, exc, value)
  File "$site/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "$site/MySQLdb/cursors.py", line 209, in execute
    r = self._query(query)
  File "$site/MySQLdb/cursors.py", line 372, in _query
    rowcount = self._do_query(q)
  File "$site/MySQLdb/cursors.py", line 335, in _do_query
    db.query(q)
  File "$site/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
_mysql_exceptions.ProgrammingError: (1146, "Table 'test_schema.i_dont_exist' doesn't exist")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "$path/test/engine/test_execute.py", line 1576, in test_legacy_dbapi_error
    conn.execute("SELECT FOO FROM I_DONT_EXIST")
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 833, in execute
    return self._execute_text(object, multiparams, params)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 982, in _execute_text
    statement, parameters
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1070, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1271, in _handle_dbapi_exception
    exc_info
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 188, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=exc_value)
  File "$path/test/../lib/sqlalchemy/util/compat.py", line 181, in reraise
    raise value.with_traceback(tb)
  File "$path/test/../lib/sqlalchemy/engine/base.py", line 1063, in _execute_context
    context)
  File "$path/test/../lib/sqlalchemy/engine/default.py", line 442, in do_execute
    cursor.execute(statement, parameters)
  File "$site/MySQLdb/cursors.py", line 220, in execute
    self.errorhandler(self, exc, value)
  File "$site/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
  File "$site/MySQLdb/cursors.py", line 209, in execute
    r = self._query(query)
  File "$site/MySQLdb/cursors.py", line 372, in _query
    rowcount = self._do_query(q)
  File "$site/MySQLdb/cursors.py", line 335, in _do_query
    db.query(q)
  File "$site/MySQLdb/connections.py", line 280, in query
    _mysql.connection.query(self, query)
sqlalchemy.exc.ProgrammingError: (ProgrammingError) (1146, "Table 'test_schema.i_dont_exist' doesn't exist") b'SELECT FOO FROM I_DONT_EXIST' ()

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "$path/test/engine/test_execute.py", line 1580, in test_legacy_dbapi_error
    eq_(canary.mock_calls[0][1][2], "SELECT FOO FROM I_DONT_EXIST")
  File "$path/test/../lib/sqlalchemy/testing/assertions.py", line 187, in eq_
    assert a == b, msg or "%r != %r" % (a, b)
AssertionError: b'SELECT FOO FROM I_DONT_EXIST' != 'SELECT FOO FROM I_DONT_EXIST'
________________ UnicodeTest_mysql_mysqldb.test_native_unicode _________________
Traceback (most recent call last):
  File "$path/test/sql/test_types.py", line 943, in test_native_unicode
    expected
  File "$path/test/../lib/sqlalchemy/testing/assertions.py", line 187, in eq_
    assert a == b, msg or "%r != %r" % (a, b)
AssertionError: True != False
=========================== short test summary info ============================
FAIL test/dialect/mysql/test_types.py::TypesTest_mysql_mysqldb::()::test_bit_50_roundtrip
FAIL test/engine/test_execute.py::CompiledCacheTest_mysql_mysqldb::()::test_cache
FAIL test/engine/test_execute.py::CompiledCacheTest_mysql_mysqldb::()::test_keys_independent_of_ordering
FAIL test/engine/test_execute.py::EngineEventsTest_mysql_mysqldb::()::test_cursor_events_ctx_execute_scalar
FAIL test/engine/test_execute.py::EngineEventsTest_mysql_mysqldb::()::test_cursor_events_execute
FAIL test/engine/test_execute.py::EngineEventsTest_mysql_mysqldb::()::test_execute_events
FAIL test/engine/test_execute.py::ExecuteTest_mysql_mysqldb::()::test_unicode_test_fails_warning
FAIL test/engine/test_execute.py::HandleErrorTest_mysql_mysqldb::()::test_exception_event_non_dbapi_error
FAIL test/engine/test_execute.py::HandleErrorTest_mysql_mysqldb::()::test_handle_error
FAIL test/engine/test_execute.py::HandleErrorTest_mysql_mysqldb::()::test_legacy_dbapi_error
FAIL test/sql/test_types.py::UnicodeTest_mysql_mysqldb::()::test_native_unicode
======= 11 failed, 1255 passed, 424 skipped, 30 error in 158.28 seconds ========

Bad exception raised for null inserts

The legacy MySQLdb1 raises an IntegrityError when doing a null insert in a not-nullable column. Apparently, this fork is raising OperationalError. The old behavior should be restored if possible.

_mysql.free_result() not necessary?

http://dev.mysql.com/doc/refman/5.7/en/mysql-free-result.html

It suggests that once you're finished using the result set, it is recommended to free it up. Is there a reason it is not a method for mysql? I tried using with conn.store_result() as result such that it runs the destructor on the result object, but it threw an AttributeError complaining there was no exit
I've been meaning to understand whether or not I can reuse the connection (ie. conn.query('something'), get results, query again, get results, query again) without opening/closing a new connection every time. I've been getting some MySQL read locks (just using SELECT statements) from the 3-6 threads I'm using to access the DB concurrently. I'm wondering if it has anything to do with not releasing the memory after each store_result() and starting another query...

If this is explained in PEP or is not relevant to the issue tracker, please let me know and close this thread. Thanks.

pyformat insert support for Python 3

It seems that with Python3, the pyformat insert doesn't work: cursor.execute("INSERT INTO table f1, f2 values(%(val1)s, %(val2)s)", {"val1": value_1, "val2": value_2})
This needs confirmation, I didn't test it myself yet.

image not found

Hello,

I'm using Mac OS X 10.10 Anaconda 3

$ pip install mysqlclient
Collecting mysqlclient
  Using cached mysqlclient-1.3.6.tar.gz
Installing collected packages: mysqlclient
  Running setup.py install for mysqlclient
Successfully installed mysqlclient-1.3.6
pc:blaze scls$ ipython
Python 3.4.3 |Anaconda 2.3.0 (x86_64)| (default, Mar  6 2015, 12:07:41)
Type "copyright", "credits" or "license" for more information.

IPython 3.2.1 -- An enhanced Interactive Python.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import MySQLdb
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-2-dd22983d5391> in <module>()
----> 1 import MySQLdb

//anaconda/lib/python3.4/site-packages/MySQLdb/__init__.py in <module>()
     17 from MySQLdb.release import __version__, version_info, __author__
     18
---> 19 import _mysql
     20
     21 if version_info != _mysql.version_info:

ImportError: dlopen(//anaconda/lib/python3.4/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
  Referenced from: //anaconda/lib/python3.4/site-packages/_mysql.so
  Reason: image not found

Kind regards

OperationalError: (2006, 'MySQL server has gone away')

I'm using mysqlclient for a web service that keeps a permanent connection to an external MySQL server.

It seems like after a few hours of continuous operation, all queries start failing with the following error:

OperationalError: (2006, 'MySQL server has gone away')

I understand this is because the connection gets interrupted for whatever reason, which is very common for long-running connections.

I remember working with some other libraries in the past which had an "auto-reconnect" feature. Does mysqlclient have anything like that? If not, what's the best practice to handle these connection issues?

cursor.executemany() does not handle percent signs correctly vs. execute()

see also similar pymysql bug at PyMySQL/PyMySQL#449

Below, a statement with percent signs succeeds for cursor.execute(), but fails for cursor.executemany() with:

_mysql_exceptions.OperationalError: (1054, "Unknown column 'A%%' in 'field list'")

Unlike the pymysql issue, adding space doesn't change anything.

def run_test(conn):
    cursor = conn.cursor()
    cursor.execute("""
        DROP TABLE IF EXISTS percent_test
    """)
    cursor.execute("""
        CREATE TABLE percent_test (
        `A%` INTEGER,
        `B%` INTEGER
    )
    """)
    cursor.execute("SHOW CREATE TABLE percent_test")
    print cursor.fetchall()

    stmt = "INSERT INTO percent_test (`A%%`, `B%%`) VALUES (%s, %s)"

    # passes
    cursor.execute(stmt, (1, 2))

    # fails
    cursor.executemany(stmt, [(3, 4), (5, 6)])

    cursor.close()
    conn.commit()

import MySQLdb
conn = MySQLdb.connect(user="scott", passwd="tiger", db="test")

run_test(conn)

Can not login MySQL 5.7.6 or higher

Same issue: farcepest/MySQLdb1#106

mysql> CREATE USER 'jeffrey'@'localhost' IDENTIFIED BY 'mypass';
Query OK, 0 rows affected (0.01 sec)

mysql> select User, Password, plugin from mysql.user where User='jeffrey';
+---------+----------+-------------------------------------------+
| User    | Password | plugin                                    |
+---------+----------+-------------------------------------------+
| jeffrey |          | *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+---------+----------+-------------------------------------------+
1 row in set (0.00 sec)

mysql> select @@version;
+-----------+
| @@version |
+-----------+
| 5.7.10    |
+-----------+
1 row in set (0.00 sec)

mysql> grant all on sentiment.* to 'jeffrey'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| item4              |
| mysql              |
| performance_schema |
| sentiment          |
| test               |
+--------------------+
6 rows in set (0.00 sec)

Python 2.7.10 (default, Sep 24 2015, 15:28:51)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.72)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>> conn = MySQLdb.connection(host='localhost', user='jeffrey', passwd='mypass', db='sentiment')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
_mysql_exceptions.OperationalError: (1524, "Plugin '*6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4' is not loaded")
$ pip freeze | grep mysql
You are using pip version 7.1.2, however version 8.0.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
mysqlclient==1.3.7

See this changes

Windows: "Unable to find vcvarsall.bat"

Hello, I joined project where is this package used. I tried to install it via pip (Python 3.4.2 64bit) on Windows 7 Pro 64bit and I get this error message:

"Unable to find vcvarsall.bat"

It is dependency in file requirements.txt so I just ran pip install -r requirements.txt.

Cursors leak on exception in python 3.3

Python 2.7, 3.4 and pypy2 2.4 (if the same GC API makes sense of it) are fine.

import gc
import MySQLdb

#gc.set_debug(gc.DEBUG_UNCOLLECTABLE)

def test():
  conn = MySQLdb.connect(user = 'guest')
  try:
    conn.cursor().execute('foo bar') 
  except:
    pass

if __name__ == '__main__':
  test()
  gc.collect()
  if gc.garbage:
    print(gc.garbage)
    print(gc.get_referrers(gc.garbage[0]))
  else:
    print('OK')

On 3.3 output is:

[<MySQLdb.cursors.Cursor object at 0x7f90a162cd90>]
[[<MySQLdb.cursors.Cursor object at 0x7f90a162cd90>], <frame object at 0x19d7b70>, <frame object at 0x192ce80>, <frame object at 0x19231a0>]

I don't have an idea how the cursor and the frames have managed to produce a reference cycle, neither how new exception semantics come into play, but it definitely has something to do with presence of __del__ in cursor. Though PyMySQL from the Cheese Shop which still has __del__ (removed in #287) is fine.

Multiple warnings during pip install

Most of the warnings seem harmless, but the incompatible pointer types worry me. On first sight it seems to work for me though.

Python 3.4.1 (default, May 19 2014, 17:23:49) 

gcc version 4.9.1 20140903 (prerelease) (GCC) 

pip install mysqlclient
Downloading/unpacking mysqlclient
  Downloading mysqlclient-1.3.3.tar.gz (77kB): 77kB downloaded
  Running setup.py (path:/home/zulan/code/django/build/mysqlclient/setup.py) egg_info for package mysqlclient

Installing collected packages: mysqlclient
  Running setup.py install for mysqlclient
    building '_mysql' extension
    gcc -pthread -Wno-unused-result -Werror=declaration-after-statement -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector-strong --param=ssp-buffer-size=4 -fPIC -Dversion_info=(1,3,3,'final',1) -D__version__=1.3.3 -I/usr/include/mysql -I/usr/include/python3.4m -c _mysql.c -o build/temp.linux-x86_64-3.4/_mysql.o -fPIC -pipe -fstack-protector-strong --param=ssp-buffer-size=4 -fno-strict-aliasing -DBIG_JOINS=1 -fomit-frame-pointer -fno-delete-null-pointer-checks -g -static-libgcc -fno-omit-frame-pointer -fno-strict-aliasing
    In file included from _mysql.c:40:0:
    /usr/include/mysql/my_config.h:437:0: warning: "HAVE_MBRTOWC" redefined
     #define HAVE_MBRTOWC
     ^
    In file included from /usr/include/python3.4m/Python.h:8:0,
                     from _mysql.c:29:
    /usr/include/python3.4m/pyconfig.h:554:0: note: this is the location of the previous definition
     #define HAVE_MBRTOWC 1
     ^
    In file included from _mysql.c:40:0:
    /usr/include/mysql/my_config.h:438:0: warning: "HAVE_WCSCOLL" redefined
     #define HAVE_WCSCOLL
     ^
    In file included from /usr/include/python3.4m/Python.h:8:0,
                     from _mysql.c:29:
    /usr/include/python3.4m/pyconfig.h:1132:0: note: this is the location of the previous definition
     #define HAVE_WCSCOLL 1
     ^
    _mysql.c: In function ‘_mysql_field_to_python’:
    _mysql.c:1370:16: warning: unused variable ‘fmt’ [-Wunused-variable]
        const char *fmt = "s#";
                    ^
    _mysql.c: In function ‘_mysql_ConnectionObject_query’:
    _mysql.c:1976:9: warning: unused variable ‘mysql’ [-Wunused-variable]
      MYSQL *mysql = &(self->connection);
             ^
    _mysql.c: In function ‘_mysql_ConnectionObject_read_query_result’:
    _mysql.c:2021:6: warning: unused variable ‘len’ [-Wunused-variable]
      int len, r;
          ^
    _mysql.c:2020:8: warning: unused variable ‘query’ [-Wunused-variable]
      char *query;
            ^
    _mysql.c: In function ‘_mysql_ConnectionObject_getattro’:
    _mysql.c:2665:33: warning: passing argument 1 of ‘PyObject_GenericGetAttr’ from incompatible pointer type
      return PyObject_GenericGetAttr(self, name);
                                     ^
    In file included from /usr/include/python3.4m/pytime.h:6:0,
                     from /usr/include/python3.4m/Python.h:65,
                     from _mysql.c:29:
    /usr/include/python3.4m/object.h:533:24: note: expected ‘struct PyObject *’ but argument is of type ‘struct _mysql_ConnectionObject *’
     PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
                            ^
    _mysql.c: In function ‘_mysql_ConnectionObject_setattro’:
    _mysql.c:2679:33: warning: passing argument 1 of ‘PyObject_GenericSetAttr’ from incompatible pointer type
      return PyObject_GenericSetAttr(self, name, v);
                                     ^
    In file included from /usr/include/python3.4m/pytime.h:6:0,
                     from /usr/include/python3.4m/Python.h:65,
                     from _mysql.c:29:
    /usr/include/python3.4m/object.h:534:17: note: expected ‘struct PyObject *’ but argument is of type ‘struct _mysql_ConnectionObject *’
     PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *,
                     ^
    _mysql.c: In function ‘_mysql_ResultObject_setattro’:
    _mysql.c:2693:33: warning: passing argument 1 of ‘PyObject_GenericSetAttr’ from incompatible pointer type
      return PyObject_GenericSetAttr(self, name, v);
                                     ^
    In file included from /usr/include/python3.4m/pytime.h:6:0,
                     from /usr/include/python3.4m/Python.h:65,
                     from _mysql.c:29:
    /usr/include/python3.4m/object.h:534:17: note: expected ‘struct PyObject *’ but argument is of type ‘struct _mysql_ResultObject *’
     PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *,
                     ^
    gcc -pthread -shared -Wl,-O1,--sort-common,--as-needed,-z,relro build/temp.linux-x86_64-3.4/_mysql.o -L/usr/lib -L/usr/lib -lmysqlclient_r -lpthread -lz -lm -lssl -lcrypto -ldl -lpython3.4m -o build/lib.linux-x86_64-3.4/_mysql.cpython-34m.so

Successfully installed mysqlclient
Cleaning up...

AssertionError when installing with pip

The package seems to install, but reports an AssertionError:

  ... snip ...
  running install_egg_info
  running egg_info
  writing dependency_links to mysqlclient.egg-info/dependency_links.txt
  writing top-level names to mysqlclient.egg-info/top_level.txt
  writing mysqlclient.egg-info/PKG-INFO
  warning: manifest_maker: standard file '-c' not found

  reading manifest file 'mysqlclient.egg-info/SOURCES.txt'
  reading manifest template 'MANIFEST.in'
  writing manifest file 'mysqlclient.egg-info/SOURCES.txt'
  Copying mysqlclient.egg-info to build/bdist.linux-x86_64/wheel/mysqlclient-1.3.7-py3.5.egg-info
  running install_scripts
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "/tmp/pip-build-d3aeac06/mysqlclient/setup.py", line 21, in <module>
      setuptools.setup(**metadata)
    File "/usr/lib64/python3.5/distutils/core.py", line 148, in setup
      dist.run_commands()
    File "/usr/lib64/python3.5/distutils/dist.py", line 955, in run_commands
      self.run_command(cmd)
    File "/usr/lib64/python3.5/distutils/dist.py", line 974, in run_command
      cmd_obj.run()
    File "/home/ben/Projects/gamestop-admin/env/lib/python3.5/site-packages/wheel/bdist_wheel.py", line 213, in run
      archive_basename = self.get_archive_basename()
    File "/home/ben/Projects/gamestop-admin/env/lib/python3.5/site-packages/wheel/bdist_wheel.py", line 161, in get_archive_basename
      impl_tag, abi_tag, plat_tag = self.get_tag()
    File "/home/ben/Projects/gamestop-admin/env/lib/python3.5/site-packages/wheel/bdist_wheel.py", line 155, in get_tag
      assert tag == supported_tags[0]
  AssertionError

  ----------------------------------------
  Failed building wheel for mysqlclient
Failed to build mysqlclient
Installing collected packages: mysqlclient
  Running setup.py install for mysqlclient
Successfully installed mysqlclient-1.3.7

Full output here: http://sprunge.us/WYXf

Vulnerable to CVE-2015-3152 when using TLS with mysql 5.5/5.6 client libs

tl;dr: mysql 5.5/5.6 client libraries have unfortunate defaults which means TLS connections can be silently man-in-the-middled - so if mysqlclient-python is used with them, is vulnerable to CVE-2015-3152.

With mysql client libraries < v5.7, if a CA certificate is specified, the client neither requires TLS/SSL, nor actually checks the CA certificate matches the hostname. This means that if the connection is MITMed and redirected to malicious mysql server instance that pretends to not support TLS, it proceeds anyway, silently leaking credentials (if using username/password rather than client cert/key).

For example when using:

  • Ubuntu 14.04 with the latest Ubuntu trusty libmysqlclient-dev package (which is libmysqlclient18 - ie mysql v5.5)
  • mysqlclient-python v1.3.7
  • mysql-server running on localhost with TLS disabled

And then running:

import MySQLdb

conn = MySQLdb.connect(
    host='localhost',
    user='foo',
    passwd='bar',
    ssl= {
        'ca': 'unrelated-ca-cert.pem',
    }
)

Expected:
Some kind of TLS error.

Actual:

Traceback (most recent call last):
  File "./mysql-test.py", line 10, in <module>
    'ca': 'unrelated-ca-cert.pem',
  File "/home/vagrant/venv/local/lib/python2.7/site-packages/MySQLdb/__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "/home/vagrant/venv/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 204, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (1045, "Access denied for user 'foo'@'localhost' (using password: YES)")

...ie our credentials were just sent in plaintext.

This means anyone can MITM a connection to eg an Amazon RDS instance from a local dev's machine (or say Heroku, where we can't set up a VPC with the RDS instance) running mysql 5.5/5.6 client libraries, and the client will be none the wiser. Note this also affects the command line mysql client too (see: http://bugs.mysql.com/bug.php?id=79862).

Thankfully this has been fixed in mysql 5.7 (ie if a CA certificate is specified it defaults to enforcing TLS and that the cert matches the hostname; see here), however we can't easily use mysql 5.7 on Ubuntu 14.04 on Heroku/Travis/....

As for mysql 5.5/5.6, recent point releases (specifically 5.5.49 and 5.6.30) have added opt-in support for enforcing TLS/CA cert verification, however neither mysqlclient-python nor MySQLdb support enabling these.

Edit: It turns out the backported libmysqlclient 5.5/5.6 fixes are insufficient to solve this after all - there's no way mysqlclient-python can be securely used with them...

Whilst recent point releases of MySQL 5.5/5.6's libmysqlclient (specifically 5.5.49 and 5.6.30) have added opt-in support for verifying the CA certificate (using MYSQL_OPT_SSL_VERIFY_SERVER_CERT):
(a) neither mysqlclient-python nor MySQLdb currently support enabling it (though there is a PR open against MySQLdb to add it: farcepest/MySQLdb1#100)
(b) even with this option enabled, if the remote server pretends to not support TLS, then the connection can be silently downgraded to non-TLS (the "enforce TLS" options from 5.7 were only backported for the command line mysql client and not the C API)

Oracle's own MySQL Python connector does support (a) (by passing ssl_verify_cert=True), however is still vulnerable to (b). I've filed an upstream MySQL bug requesting further libmysqlclient 5.5/5.6 backports of the 5.7 fixes.

As such at the moment, there is no secure way to use mysqlclient-python, MySQLdb or MySQL Connector Python with libmysqlclient 5.5/5.6.

See also:
https://dev.mysql.com/doc/refman/5.5/en/mysql-options.html
https://dev.mysql.com/doc/refman/5.6/en/mysql-options.html
http://www.ocert.org/advisories/ocert-2015-003.html
https://mariadb.org/information-on-the-ssl-connection-vulnerability-of-mysql-and-mariadb-2/

Add link to docs in project description

Right now, the only link to the docs is at the very bottom of the Readme.

A lot more convenient if there was also a docs link in the Github project description--the 1-2 sentence blurb they show at the top of the repo.

For example, see how Flask-SQLAlchemy does it.

Support MySQL 5.7 on OS X

Installing this package seems to hard-code a reference to libmysqlclient.18.dylib in the _mysql.so, but MySQL 5.7 uses libmysqlclient.20.dylib. If I use the MySQL-python package it correctly resolves to libmysqlclient.20.dylib so I'm using that as a workaround for now.

mysqlclient and _mysql mismatch

Upgrading debian broke my mysqlclient in two apps (Flask and Django). It was working like a charm before.

ImportError: this is MySQLdb version (1, 3, 7, 'final', 1), but _mysql is version (1, 2, 3, 'final', 0)`

I have tried installing from repo but still does not work.

How can I install mysqlclient for matching this _mysql version?

lsb_release -a
No LSB modules are available.
Distributor ID: Debian 
Description:    Debian GNU/Linux 8.3 (jessie)
Release:    8.3
Codename:   jessie


mysql  Ver 14.14 Distrib 5.5.47, for debian-linux-gnu (x86_64) using readline 6.3

Clarify license

Hi, can you include in the README or somewhere similar what GPL versions are permitted?

The license file is just version 2, the INSTALL file just says "GPL" without specifying a version, and _mysql.c specifies v2 or later.

Thanks!

Why does not work delimiter statement in query?

I just want to create a stored procedure through of MySQLdb, but I get an Syntaxerror when I try it.
I tried with

cursor.execute("DELIMITER //")

and the same error occurs.
May be a stupid question, but, can someone explain why this happens?

...
...
cursor.execute("""
    DELIMITER //
    CREATE PROCEDURE test()
    BEGIN
        SELECT 1 FROM DUAL;
    END//
    DELIMITER ;
""")

DROP PROCEDURE IF EXISTS produces ProgrammingError instead of Warning

Maybe this is more of a question than an actual issue, sorry about that.

I am attempting to solve this issue: evetrivia/thanatos#15

Which errors out when running the following SQL: https://github.com/evetrivia/thanatos/tree/master/thanatos/database/procs

The MySQL documentation says that the IF EXISTS clause is an extension and that it will throw an error. OK fine. Everything online seems to say it should throw a Warning exception though, not a ProgramingError.

Reference:

Is there a reason why this causes a ProgrammingError instead of a Warning? What is the best way to handle it?

Two cases of "UnicodeDecodeError" errors

I am using mysqlclient-python 1.3.5 with django and I am getting the following errors.

The interesting part of the traceback for the first error is:

Traceback (most recent call last):
  ...
  File "/path/to/myproject/myapp/admin.py", line 44, in export_action
    for obj in queryset:
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 141, in __iter__
    self._fetch_all()
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 966, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 265, in iterator
    for row in compiler.results_iter():
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 700, in results_iter
    for rows in self.execute_sql(MULTI):
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql
    cursor.execute(sql, params)
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 129, in execute
    return self.cursor.execute(query, args)
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 219, in execute
    self.errorhandler(self, exc, value)
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/connections.py", line 38, in defaulterrorhandler
    raise errorvalue
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 205, in execute
    r = self._query(query)
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 373, in _query
    self._post_get_result()
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 377, in _post_get_result
    self._rows = self._fetch_row(0)
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 345, in _fetch_row
    return self._result.fetch_row(size, self._fetch_type)
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/connections.py", line 233, in string_decoder
    return s.decode(string_decoder.charset)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position 44: unexpected end of data

I was also getting a similar error with version 1.3.4, which I thought that was solved after upgrading to 1.3.5 (the error stopped after upgrading). But now (one day after the upgrade, without any change) the same error hits again. The intersting part of the traceback for that error is:

Traceback (most recent call last):
  ...
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 122, in __len__
    self._fetch_all()
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 966, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/query.py", line 265, in iterator
    for row in compiler.results_iter():
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 700, in results_iter
    for rows in self.execute_sql(MULTI):
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql
    cursor.execute(sql, params)
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/path/to/virtualenv/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 129, in execute
    return self.cursor.execute(query, args)
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 219, in execute
    self.errorhandler(self, exc, value)
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/connections.py", line 38, in defaulterrorhandler
    raise errorvalue
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 205, in execute
    r = self._query(query)
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 373, in _query
    self._post_get_result()
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 377, in _post_get_result
    self._rows = self._fetch_row(0)
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/cursors.py", line 345, in _fetch_row
    return self._result.fetch_row(size, self._fetch_type)
  File "/path/to/virtualenv/lib/python3.4/site-packages/MySQLdb/connections.py", line 233, in string_decoder
    return s.decode(string_decoder.charset)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 1: invalid continuation byte

Any hint?

Not working with python 3.5

This is the error I get when I try installing mysqlclient. I am using Windows and python 3.5.

Installing 'mysqlclient'
Collecting mysqlclient
  Using cached mysqlclient-1.3.6.tar.gz
Installing collected packages: mysqlclient
  Running setup.py install for mysqlclient
    Complete output from command "c:\users\buccaneer\documents\visual studio            2013\Projects\del1\del1\envrm\Scripts\python.exe" -c "import setuptools, tokenize;__file__='C:\\Users\\BUCCAN~1\\AppData\\Local\\Temp\\pip-build-wuhkxhu3\\mysqlclient\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\BUCCAN~1\AppData\Local\Temp\pip-3jbluuk2-record\install-record.txt --single-version-externally-managed --compile --install-headers "c:\users\buccaneer\documents\visual studio 2013\Projects\del1\del1\envrm\include\site\python3.5\mysqlclient":
running install
running build
running build_py
creating build
creating build\lib.win32-3.5
copying _mysql_exceptions.py -> build\lib.win32-3.5
creating build\lib.win32-3.5\MySQLdb
copying MySQLdb\__init__.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\compat.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\converters.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\connections.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\cursors.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\release.py -> build\lib.win32-3.5\MySQLdb
copying MySQLdb\times.py -> build\lib.win32-3.5\MySQLdb
creating build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\__init__.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\CR.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\ER.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.5\MySQLdb\constants
copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.5\MySQLdb\constants
running build_ext
building '_mysql' extension
error: Unable to find vcvarsall.bat

When closed, cursor.execute() raises TypeError; expect ProgrammingError

mysqlclient==1.3.6

In the following script, cursor.execute() is called on a closed cursor. The results is "TypeError: 'NoneType' object is not callable" but one expects a ProgrammingError. It looks as though errorhandler is assigned to None when closed in BaseCursor.close(). Full output below:

import MySQLdb

conn = MySQLdb.connect(user='root', db='mytest')
with conn.cursor() as cursor:
    cursor.execute('select 1')
cursor.execute('select 1')
$ venv/bin/python test.py
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    cursor.execute('select 1')
  File "/home/jon/venv/lib/python2.7/site-packages/MySQLdb/cursors.py", line 181, in execute
    while self.nextset():
  File "/home/jon/venv/lib/python2.7/site-packages/MySQLdb/cursors.py", line 133, in nextset
    db = self._get_db()
  File "/home/jon/venv/lib/python2.7/site-packages/MySQLdb/cursors.py", line 166, in _get_db
    self.errorhandler(self, ProgrammingError, "cursor closed")
TypeError: 'NoneType' object is not callable

Getting iter error for server side cursors

For a server side cursor c

    c.execute(SELECT_STATEMENT)
    temp_d = dict((i, row) for i, row in enumerate(c))

produces the following error

    temp_d = dict((i, row) for i, row in enumerate(c))
TypeError: iter() returned non-iterator of type 'SSDictCursor'

This is with python 3.4.

Error installing on Mac OS X

Python 3:

Error loading MySQLdb module: dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
  Referenced from: /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/_mysql.so
  Reason: image not found

Python 2:

Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
  Referenced from: /Library/Python/2.7/site-packages/_mysql.so
  Reason: image not found

lib{ssl,crypto,z} images not found on MacOS X 10.11

I installed with pip install mysqlclient and tried the following command and got the following traceback:

(/hlpUsers/awatts/venvs/django_bcs)awatts@slate:~/venvs/django_bcs/CrowdExp$ ./manage.py inspectdb --database=sprrunner

Traceback (most recent call last):
  File "/hlpUsers/awatts/venvs/django_bcs/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 25, in <module>
    import MySQLdb as Database
  File "/hlpUsers/awatts/venvs/django_bcs/lib/python3.4/site-packages/MySQLdb/__init__.py", line 19, in <module>
    import _mysql
ImportError: dlopen(/hlpUsers/awatts/venvs/django_bcs/lib/python3.4/site-packages/_mysql.so, 2): Library not loaded: libssl.1.0.0.dylib
  Referenced from: /hlpUsers/awatts/venvs/django_bcs/lib/python3.4/site-packages/_mysql.so
  Reason: image not found

Checking the library dependencies:

(/hlpUsers/awatts/venvs/django_bcs)awatts@slate:~/venvs/django_bcs/CrowdExp$ otool -L /hlpUsers/awatts/venvs/django_bcs/lib/python3.4/site-packages/_mysql.so
/hlpUsers/awatts/venvs/django_bcs/lib/python3.4/site-packages/_mysql.so:
    /usr/local/opt/mariadb/lib/libmysqlclient.18.dylib (compatibility version 18.0.0, current version 18.0.0)
    libz.1.dylib (compatibility version 1.0.0, current version 1.2.8)
    libssl.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0)
    libcrypto.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1226.10.1)
    /usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 913.0.0)

And checking what versions of the libraries exist:

(/hlpUsers/awatts/venvs/django_bcs)awatts@slate:~/venvs/django_bcs/CrowdExp$ ls -l /usr/lib/libssl*
-rwxr-xr-x  1 root  wheel  404656 Dec  3 01:34 /usr/lib/libssl.0.9.7.dylib
-rwxr-xr-x  1 root  wheel  629056 Dec  3 01:34 /usr/lib/libssl.0.9.8.dylib
lrwxr-xr-x  1 root  wheel      18 Jan  6 16:11 /usr/lib/libssl.dylib -> libssl.0.9.8.dylib
(/hlpUsers/awatts/venvs/django_bcs)awatts@slate:~/venvs/django_bcs/CrowdExp$ ls -l /usr/lib/libcrypto*
-rwxr-xr-x  1 root  wheel  2114976 Dec  3 01:34 /usr/lib/libcrypto.0.9.7.dylib
-rwxr-xr-x  1 root  wheel  2682800 Dec  3 01:33 /usr/lib/libcrypto.0.9.8.dylib
lrwxr-xr-x  1 root  wheel       21 Jan  6 16:11 /usr/lib/libcrypto.dylib -> libcrypto.0.9.8.dylib
(/hlpUsers/awatts/venvs/django_bcs)awatts@slate:~/venvs/django_bcs/CrowdExp$ ls -l /usr/lib/libz*
lrwxr-xr-x  1 root  wheel      12 Jan  6 16:11 /usr/lib/libz.1.1.3.dylib -> libz.1.dylib
lrwxr-xr-x  1 root  wheel      12 Jan  6 16:11 /usr/lib/libz.1.2.5.dylib -> libz.1.dylib
-rwxr-xr-x  1 root  wheel  177392 Dec  3 01:34 /usr/lib/libz.1.dylib
lrwxr-xr-x  1 root  wheel      12 Jan  6 16:11 /usr/lib/libz.dylib -> libz.1.dylib

Due to SIP (System Integrity Protection) I can't even copy or link newer versions into /usr/lib/

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.