Quantcast
Channel: MySQL Forums - Connector/Python
Viewing all 387 articles
Browse latest View live

transactions in python mysql connector (no replies)

$
0
0
Hey all,

I'm pretty confused, I hope someone can help me.

On this page, it explains how to insert data using the python connector:

http://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html

This page does not make use of the start_transaction method, even though the post states that autocommit is disabled for this example: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-start-transaction.html

Does the execute() method start a transaction?

When I try running an INSERT and then a COMMIT from the command line tool, the COMMIT says '0 rows affected'. I assume this is because I didn't start a transaction. Is the documentation above regarding inserting data with the connector missing the call to start_transaction()?

Thanks for any help!

-Jeff

Can I use MySQL Connectot/Python with 3.4.1 release? (2 replies)

No password assigned during MySQL install (2 replies)

$
0
0
Hello, I just installed MYSQL and the Python MySQL connector on my Mac OSX Pro. The installations appeared to have proceeded smoothly. During the install I was not prompted to enter a MySQL password. How do I determine what my password is? Is there a default password? I am attempting to use the Python mysql connector but am receiving an error message and I am wondering if it is because I do not know what password to enter. Here is my code and associated error message.

>>> import mysql.connector
>> conn = mysql.connector.connect(host='localhost', user='root', passwd='python')

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
conn = mysql.connector.connect(host='localhost', user='root', passwd='python')
File "/Library/Python/2.7/site-packages/mysql/connector/__init__.py", line 98, in connect
return MySQLConnection(*args, **kwargs)
File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 118, in __init__
self.connect(**kwargs)
File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 382, in connect
self._open_connection()
File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 345, in _open_connection
self._socket.open_connection()
File "/Library/Python/2.7/site-packages/mysql/connector/network.py", line 386, in open_connection
errno=2003, values=(self.get_address(), _strioerror(err)))
InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (61 Connection refused)
>>>

I am using the Programming Python text by Mark Lutz as my guide / text and the code I am copying used python as the password. If anybody could help me understand how to make the MySQL connection work properly I would appreciate it. I am just guessing that my problem is an incorrect password.

Getting XML and/or JSON strings (objects) using the Connector/Python. (2 replies)

$
0
0
Is there any way of getting XML and/or JSON strings (objects) using the Connector/Python today?

Thanks

Ernest Bonat, Ph.D.

What happen when conn pool size reached max? (2 replies)

$
0
0
Hi,

What happen to the caller/client thread execution if it requests a
connection but the pool has already reached to it's max size? Will the
caller thread block until the next connection is available form the pool?

Thanks,
Zemian

mysql.connector.django is leaking connection (2 replies)

$
0
0
Hi,

I am using latest python-connector 1.2.2. I see a connection been created inside DatabaseWrapper.__init__ from mysql/connector/django/base.py file (line 465). I don't see how this connection is clean up and close?

By watching the MySQL processlist, I see that any django app that accesses the DB will start leaking connections. Is this a known issue?

Thanks,
Zemian

Connector/Python with mysqlfabric shard is very slow to execute statement (no replies)

$
0
0
The Connector/Python with mysqlfabric shard is very slow.

a shard table on many servers,

when call set_propery(),it close the connector and add it to the pool,

when getting cursor, it reinit anoter pool connecotr on anoter shard server


every statement, first close,and then open, although I use connetor pool,

But it is very slow.

The connection can be cached ?

Error when executing any query on CentOS 5.4: "Failed parsing EOF packet" (no replies)

$
0
0
Hello,

I'm assuming I can post issues regarding MySQL Connector/Python here. Any help in debugging this issue is appreciated. I'm afraid though that it's caused by my environment, making it harder to reproduce. Let me know if you need any additional information.

Basically, I installed MySQL Connector/Python without a problem on CentOS 5.4, using Python 2.7.7. I'm able to import mysql.connector and initialize a connection using mysql.connector.connect(). According to the is_connected method, I'm indeed connected to the database.

However, as soon as I execute any SQL query, whether by using a cursor object or something else that runs a SQL command behind the scenes (e.g. get_database method), I run into the following error:
mysql.connector.errors.InterfaceError: Failed parsing EOF packet.

Apparently, the database connection is lost after this, according to the is_connected method. Below is a copy of an interactive Python session showing this. N.B. I'm using the Anaconda Python distribution here, but the same issue exists with a vanilla installation of Python.


>>> import mysql.connector
>>> cnx = mysql.connector.connect(<database information here>)
>>> cnx.is_connected()
True
>>> cnx.get_database()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/bgrande/software/genesis/anaconda-2.0.1/lib/python2.7/site-packages/mysql/connector/connection.py", line 1200, in get_database
return self._info_query("SELECT DATABASE()")[0]
File "/home/bgrande/software/genesis/anaconda-2.0.1/lib/python2.7/site-packages/mysql/connector/connection.py", line 1434, in _info_query
cursor.execute(query)
File "/home/bgrande/software/genesis/anaconda-2.0.1/lib/python2.7/site-packages/mysql/connector/cursor.py", line 494, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/home/bgrande/software/genesis/anaconda-2.0.1/lib/python2.7/site-packages/mysql/connector/connection.py", line 683, in cmd_query
statement))
File "/home/bgrande/software/genesis/anaconda-2.0.1/lib/python2.7/site-packages/mysql/connector/connection.py", line 612, in _handle_result
eof = self._handle_eof(self._socket.recv())
File "/home/bgrande/software/genesis/anaconda-2.0.1/lib/python2.7/site-packages/mysql/connector/connection.py", line 554, in _handle_eof
eof = self._protocol.parse_eof(packet)
File "/home/bgrande/software/genesis/anaconda-2.0.1/lib/python2.7/site-packages/mysql/connector/protocol.py", line 252, in parse_eof
raise errors.InterfaceError(err_msg)
mysql.connector.errors.InterfaceError: Failed parsing EOF packet.
>>> cnx.get_database()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/bgrande/software/genesis/anaconda-2.0.1/lib/python2.7/site-packages/mysql/connector/connection.py", line 1200, in get_database
return self._info_query("SELECT DATABASE()")[0]
File "/home/bgrande/software/genesis/anaconda-2.0.1/lib/python2.7/site-packages/mysql/connector/connection.py", line 1433, in _info_query
cursor = self.cursor(buffered=True)
File "/home/bgrande/software/genesis/anaconda-2.0.1/lib/python2.7/site-packages/mysql/connector/connection.py", line 1328, in cursor
raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.
>>> cnx.is_connected()
False

Exception error when trying to close mysql connection (no replies)

$
0
0
Hi,

I get this when calling the function to close the connection
.
.
.
File "mysql\connector\locales\__init__.pyc", line 54, in get_client_error
ImportError: No localization support for language 'eng'

I am using py2exe.
Any ideas?
Thank you

Help with getting Python Connector working (no replies)

$
0
0
After trying many things I continue to get errors using the Python Connector.

MySQL works fine in my installation & has for a few years. Python as well. The Path & other system variables seem to be ok. I've put all these below and would like some assitance in getting this to work. Since I work alone, there is no other person locally to seek help from in MySQL or Python individually.

Path is:
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;G:\MySQL\MySQL Utilities 1.3.6\;C:\Python34\;C:\MysqlConnector\

OS is:
Win Server 2012 R2 Essentials

Where & which file used to install:
MySQL installation: G:\MySQL\MySQL Server 5.6
Python: C:\Python34
Connector: C:\MysqlConnector

File versions:
mysql-installer-community-5.6.19.0.msi
python-3.4.2.msi
mysql-connector-pyton-2.0.2-py3.4.msi

Proper Python installation:
C:\>python
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:15:05) [MSC v.1600 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from distutils.sysconfig import get_python_lib
>>> print(get_python_lib())
C:\Python34\Lib\site-packages
>>>

Simple connect & error:
# -*- coding: utf-8 -*-
# MySQL Workbench Python script
# <description>
# Written in MySQL Workbench 6.1.6

import mysql.connector

cnx = mysql.connector.connect(user='root', password='**********', database='aes')

# do things

cns.close()

Uncaught exception while executing C:\Python34\Scripts\MyFirstTests.py:
File "c:\python34\scripts\myfisttests.py", line 8, in <module>
import mysql.connector
ImportError: No module named mysql.connector


Would appreciate any help,

Rich

mysql connector python. error at instalation (no replies)

$
0
0
hello,
run the file .msi , a window opens and closes, and only installs three text files.

the other way, error message:
python 2.7 required which was not found in the registry.

modify records, nothing happens

any solution?

what I'm wrong (2 replies)

$
0
0
try:
conn = mysql.connector.connect(
host=investcfg.host,
user=investcfg.user,
password=investcfg.pw,
database=investcfg.db,
charset=investcfg.charset)

except mysql.connector.Error as err:
print "Error %d: %s" % (err.args[0], err.args[1])
sys.exit(1)

cursor = conn.cursor()
wdate = datetime.date(2014,12,7)

try:
cursor.execute("Delete from Prices_tmp where `Code` not in " +
"(select Code from Stocks b)")

cursor.execute("Delete from `Prices_tmp` where `Code` in " +
"(select b.`Code` from `Prices` b where b.`Code` = %s)", (wdate))

except mysql.connector.Error as err:
print "Error %d: %s" % (err.args[0], err.args[1])
cursor.close()
conn.close()
sys.exit(1)

cursor.close()
conn.close()

I get the error for the about script.

Error 1064: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1

may I know how to pass date parameter to the script? what is wrong is it? I user lubuntu 14.04. Python 2.7.8?

mysql.connector not supported? (no replies)

$
0
0
I using lubuntu 14.04 in a hyper-v virtual machine. I installed mysql-connector-python 2.0.2-1ubuntu14.04. It work find with my python 2 script. I try whether I can migrate my script to python 3.4. I get message "ImportError: No mudule named 'mysql'? It is not supported or I miss something.

Python Connector Create Tables Error (2 replies)

$
0
0
Hi all,

I am a new user and in need of some help. I have posted the code in question below. I am receiving the following error code. I have checked the syntax and verified against the tutorial given in the documents. I am struggling to see where I am going wrong. Many thanks

Creating table leg_data: Cannot add foreign key constraint
Creating table master: OK


from __future__ import print_function
import mysql.connector
from mysql.connector import errorcode

cnx = mysql.connector.connect(user='', password='', host='')

cursor = cnx.cursor()

DB_NAME = 'TEST'

def create_database(cursor):
try:
cursor.execute(
"CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME))
except mysql.connector.Error as err:
print("Failed creating database: {}".format(err))
exit(1)

try:
cnx.database = DB_NAME
except mysql.connector.Error as err:
if err.errno == errorcode.ER_BAD_DB_ERROR:
create_database(cursor)
cnx.database = DB_NAME
else:
print(err)
exit(1)

TABLES={}
TABLES['master'] = (
"CREATE TABLE `master` ("
" `request_no` int(11) NOT NULL AUTO_INCREMENT,"
" `distance` int NOT NULL,"
" `duration` int NOT NULL,"
" `duration_in_traffic` int NOT NULL,"
" `Orig_lat` double NOT NULL,"
" `Orig_lng` double NOT NULL,"
" `Orig_address` longtext ,"
" `Dest_lat` double NOT NULL,"
" `Dest_lng` double NOT NULL,"
" `Dest_address` longtext ,"
" `summary` text ,"
" PRIMARY KEY (`request_no`)"
") ENGINE=InnoDB")

TABLES['leg_data'] = (
"CREATE TABLE `leg_data` ("
" `leg_no` int(11) NOT NULL AUTO_INCREMENT,"
" `request_no` int(11),"
" `summary` text ,"
" `warnings` text ,"
" `leg_distance` int ,"
" `leg_duration` int ,"
" `leg_travel_mode` longtext ,"
" `leg_Orig_lat` double ,"
" `leg_Orig_lng` double ,"
" `leg_Dest_lat` double ,"
" `leg_Dest_lng` double ,"
" `leg_html_inst` longtext ,"
" `leg_polyline` longtext ,"
" PRIMARY KEY (`leg_no`),"
" CONSTRAINT `master_ibfk` FOREIGN KEY (`request_no`)"
" REFERENCES `master` (`request_no`)"
") ENGINE=InnoDB")

for name, ddl in TABLES.iteritems():
try:
print("Creating table {}: ".format(name), end='')
cursor.execute(ddl)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print("already exists.")
else:
print(err.msg)
else:
print("OK")

cursor.close()
cnx.close()

mysql.connector.django doesn't work with django 1.8 (3 replies)


mysql.connector for binary file save to blob field (2 replies)

$
0
0
Hi, everyone.

It is my first time to ask for help here.

I use Python 3.4 to try save some imaging file to the longblob field of mysql table. The codes are:

====
import mysql.connector

filename = 'd:/12.jpeg'
print(filename)

f = open(filename, 'rb')
photo = f.read()
f.close()

mydb = mysql.connector.connect(host = '192.168.1.15', database = 'simon', user = 'simon', password = '1234')
mycur = mydb.cursor()

mycur.execute("insert into brand (imaging) values ('%s')", ([photo]))

mydb.commit()

mycur.close()
mydb.close()

======

When I run the code, it is always responsed some error message:

====
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '???' at line 1
====

I really need help for this matter.

Thank you in advance.

Simon

Python Connector (1 reply)

$
0
0
Hello All,

I am having an issue with the Python connector that I was hoping someone might be able to shed some light on. First off I am running Kubuntu 14.04 LTS with Python 3.4.0 and MySQL 5.5.43. I have manually gone into MySQL to make my tables and columns:

mysql> show tables
-> ;
+---------------------+
| Tables_in_Firewalls |
+---------------------+
| Host |
| Host_History |
+---------------------+
2 rows in set (0.00 sec)

mysql> Describe Host;
+-----------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------+------+-----+---------+----------------+
| Firewall_ID | int(11) | NO | MUL | NULL | auto_increment |
| Session | varchar(30) | NO | | NULL | |
| Hostname | varchar(25) | NO | | NULL | |
| Address | varchar(15) | NO | | NULL | |
| Status | varchar(10) | NO | | NULL | |
| SmartNet | enum('Y','N') | YES | | NULL | |
| Contract_Level | varchar(15) | YES | | NULL | |
| Contract_Expire | date | YES | | NULL | |
| Site_Name | varchar(30) | NO | | NULL | |
| Installed | date | YES | | NULL | |
+-----------------+---------------+------+-----+---------+----------------+
10 rows in set (0.00 sec)

mysql> Describe Host_History;
+---------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| Firewall_ID | smallint(6) | NO | | NULL | |
| Implemented | date | NO | | NULL | |
| Make | varchar(10) | NO | | NULL | |
| Model | varchar(10) | NO | | NULL | |
| Serial_Number | varchar(20) | NO | | NULL | |
| Version | varchar(10) | NO | | NULL | |
| Memory | smallint(6) | NO | | NULL | |
+---------------+-------------+------+-----+---------+-------+
7 rows in set (0.00 sec)

My script connects to the database just fine with

FirewallDB = mysql.connector.connect(user = 'UserID', password = 'password', host = '127.0.0.1', database = 'Firewalls')
Cursor = FirewallDB.cursor()

Per the manual I then create a string for a query:

Query = ("SELECT Session FROM Host AS H WHERE H.Session = FileTemplate")
Cursor.execute (Query)

I originally had the Query string quoted with two individual lines similar to the example:

query = ("SELECT first_name, last_name, hire_date FROM employees "
"WHERE hire_date BETWEEN %s AND %s")

But I found that Python did not like this even if a + was inserted between the two quoted strings. After altering the Query string a few times based on various error messages, the latest errors I am seeing are:

* Unknown column 'FileTemplate' in 'where clause'

I replaced 'FileTemplate' with a %s and changed my Cursor.execute(Query, (FileTemplate)) so now I am getting:

* mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1

I added a Cursor.commit() after the execute, but this didn't seem to matter. It appears that my variable 'FileTemplate' is going to be seen by MySQL as a column unless I use a %s and substitute. I am unsure of why I am getting a syntax error.

Error 10053 (lost connection) at COMMIT after long SELECT (no replies)

$
0
0
I'm running a long job in Python which has done a SELECT which returns about 2.2 million rows. The rows are read with "readmany" in blocks of 25,000. A block of rows is read about every 10 minutes. That works fine.

After all the records are read, the program does a COMMIT to release the state held by the SELECT. (Repeatable-read mode.) This fails:

891:58.54 [MainThread] FAILED: OperationalError(2006, "MySQL server has gone away (ConnectionAbortedError(10053, 'An established connection was aborted by the software in your host machine', None, 10053, None))")
Traceback (most recent call last):
File "c:\python34\lib\site-packages\pymysql\connections.py", line 914, in _write_bytes
self.socket.sendall(data)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

Traceback (most recent call last):
File "..\InfoCompanyDb.py", line 179, in reparseindex
self.reparsefails(dbinfo)
File "..\InfoCompanyDb.py", line 337, in reparsefails
self.db.commit()
File "c:\python34\lib\site-packages\pymysql\connections.py", line 705, in commit
self._execute_command(COMMAND.COM_QUERY, "COMMIT")
File "c:\python34\lib\site-packages\pymysql\connections.py", line 957, in _execute_command
self._write_bytes(prelude + sql[:chunk_size-1])
File "c:\python34\lib\site-packages\pymysql\connections.py", line 916, in _write_bytes
raise err.OperationalError(2006, "MySQL server has gone away (%r)" % (e,))
pymysql.err.OperationalError: (2006, "MySQL server has gone away (ConnectionAbortedError(10053, 'An established connection was aborted by the software in your host machine', None, 10053, None))")

This isn't a networking problem; host and client are on the same Windows 7 machine (this is a test environment).
The database connection hasn't been idle; it's been used every 10 minutes for almost 24 hours as rows are read with "readmany". But
no new command has been sent for almost a day. Should the connection time out like that? Is there something I can do during this big SELECT to keep the connection alive?

Windows 7
MySQL Server and client on same machine
Server version: 5.1.47-community MySQL Community Server (GPL)
Python connector PyMySQL

Configuring MySQL Connector/Python to Function with Python 3.4 (no replies)

$
0
0
I installed MySQL Connector/Python. When I type in python and then enter "import mysql.connector" it works. Now that is with Python 2.7.6.

To access Python 3.4.0, I typed in python3. I then entered "import mysql.connector". In this instance, it failed with the error message: "ImportError: No module named 'mysql'".

How can Python 3.4.0 or the connector be tweaked to successfully import "mysql.connector"?

Adding new sproc to the exisiting database using connectors? (no replies)

$
0
0
Just a little explanation needed.

The project I'm currently working on is mostly pythonic, by this reason I'll likely use mysqldb python connector or sqlalchemy.

The question arose when I've tried to find out the way of adding new sproc to my database via those connectors. I've found a dozens of examples of how to call an existing sprocs from a database but none of how to actually add (create) a new one by them.

I kept on googling and have found text() construct in sqlalchemy, this one enables me to write raw sql code, so IMO, can be used for adding a new sproc to the existing db.

Generally speaking there always is a direct way to do so by using mysql shell or workbench editor. But how can this task be achieved with mysqldb python connector(if at all)?

Is it a good/weird practice to add new sproc that way?

Your help will be highly appreciated.

Thanks in advance, Ivan.
Viewing all 387 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>