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

(Beginner) Python cannot import name FabricShard (no replies)

$
0
0
MySQL VERSION 5.7
Python version 2.7.5
mysqlfabric version 1.5.6
python connector version 2.1.6

I am able to located the place of declaration of FabricMySQLServer but not of FabricShard. Searched every file inside python folder for FabricShard but couldn't find it declared anywhere. How do i tackle the import error for FabricShard?

store and retrieve text file in mysql database by using python (2 replies)

$
0
0
Hello everyone,
could you help me to store and retrieve text file in MySQL database,
Thank you

Implementing a Menu in python to MySQL database (1 reply)

$
0
0
code for my menu, but how to implement?

import _mysql



buffer = "true"



def oneQuery():
db = _mysql.connect(host="localhost",user="root",passwd="password123",db="mmorpgs")
db.query("""SELECT * FROM games;""")
r = db.store_result()
nR = r.num_rows()
while(nR > 0):
print(r.fetch_row())
nR = nR - 1
db.close()

def twoQuery():
db = _mysql.connect(host="localhost",user="root",passwd="password123",db="mmorpgs")
db.query("""SELECT * FROM developer;""")
r = db.store_result()
nR = r.num_rows()
while(nR > 0):
print(r.fetch_row())
nR = nR - 1
db.close()

def threeQuery():
db = _mysql.connect(host="localhost",user="root",passwd="password123",db="mmorpgs")
#db.query("""SELECT * FROM genre WHERE genreID NOT IN (SELECT * FROM genre as a, ownership AS b WHERE
# a.genreID = b.genreID;)""")
db.query("""SELECT genreID FROM genre WHERE genreID not in (select genreID from ownership)""")
r = db.store_result()
nR = r.num_rows()
while(nR > 0):
print(r.fetch_row())
nR = nR - 1
if nR == 0:
print("""all genres have at least 1 developer and game title""")
db.close()

while buffer:
print("""
0.Exit
1.See games
2.See developers
3.See if a genre has no current listing of games
""")
buffer=input("what would you like to do? ")
if buffer == 1:
oneQuery()
if buffer == 2:
twoQuery()
if buffer == 3:
threeQuery()


Is my menu code, but how do I go about actually connecting this code to my database in mysql?

Prepared Cursors, raw=True? (no replies)

$
0
0
I'm comparing results from two MySQL databases with Python. The first database query is batch, to retrieve all the comparison records from the source, so I didn't prepare it. I'm getting back Unicode strings for the most part, as expected (use_unicode=True).

The target query is run once per record, so I'm using a cursor with prepared=True. The results I'm getting back from this cursor are bytearrays, so they don't match without conversion.

Is it true that prepared cursors in Connector/Python return raw values? Seems to be what I'm seeing. Doesn't change anything if I set raw=False. I can't find anything in the documentation that suggests this is true, but ... seems to be experimentally true.

Lpad not supporting %s in Python (no replies)

$
0
0
Hi,

I am trying to query:
cursor.execute("Select Lpad (%s,5,0)", (24))

which results in error:
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,5,0)' at line 1

Same query executes successfully as:
cursor.execute("Select Lpad (24,5,0)")

Platform: Windows
Lib. Build: mysql-connector-python-2.1.6-py2.7-winx64
Python: 2.7.13

shall I get some advice about using MySQL by Python3? (no replies)

$
0
0
i am newbie for MySQL, and now I want to use MySQL by python3;
shall I get some advice for this?

Can't Get Result Set as Dictionary (1 reply)

$
0
0
So I'm using MySQL Connector/Python version 2.1.7 to execute a stored procedure. Result set is coming as list of tuples, which is expected. I need column names, so I'm using "dictionary=True" in the cursor declaration per the docs. However, still only returns list of tuples. Docs say it should work since version 2.0.0 of connector.

Here is code:

import mysql.connector
proc = 'audit_report'
parms = [data['schoolid'], dateToISO(data['startdatedefault'],'from'), dateToISO(data['enddatedefault'],'to'), joinIntList(data['studypgms'], joinWith), joinIntList(data['fedpgms'], joinWith), joinIntList(data['statuses'], joinWith), data['fullssndefault']]
conn = mysql.connector.connect(user='myUser', database='myDB', password='myPwd')
cursor = conn.cursor(dictionary=True)
cursor.callproc(proc, parms)

for result in cursor.stored_results():
print(result.fetchall())

So I get the list of tuples, not the list of dictionaries.
Any ideas why this won't work? Is it because I'm calling a store proc instead of executing sql code?

The stored procedure is complex, so there are multiple tables, and crosstabs. Result column names appear just fine when I execute the procedure in MySQL Workbench.

Thanks...

Beginner's mistake? removeConnections doesn't release the pool connections (no replies)

$
0
0
I am using mysql.connector.pooling.MySQLConnectionPool to create a connection pool and before exiting the app, I wanted to release the connections.

So I called mysql.connector.pooling._removeConnections() to release the pool connections but unfortunately, if I check the number of connections using 'show status' on MySQL server, the number remains the same.

What should ideally be done here to release the connections?

Legacy python sql connector pool (no replies)

$
0
0
I have been asked to make changes to a legacy python app which uses Python 2.4, MySQL 1.2.2 and wxpython.
This is built into an installer using py2exe -> nsis.
The original developer cannot be contacted for advice.

There appears to be a missing module preventing me from running or building the app:
missing module ‘pool’.

It is typically used like this:

import pool

db_connection_pool = pool.Pool(lambda:db.open_connection(db=dbtouse))

def open_connection(id="root", password="__rtk__", user_name="",
db=constants.database_name):
instance = MySQLdb.Connect(user=id, passwd=password, db=db)
connection = DBConnection(instance, id, password, user_name)
return connection

It looks like there is a missing SQL connector pool module but I have no idea what it is.
I have tried everything to no avail:

a. processing.Pool or multiprocessing.Pool - TypeError: range() integer end argument expected, got function
b. Pysqlpool – no Pool()
c. SQLAlchemy - 'Pool' object has no attribute 'get'
d. Antiorm - pool = ConnectionPool()
e. SQLRelay – no Pool()
f. Mysql - .connector.pooling
g. psycopg2.pool – no Pool()
h. DBUtils - no Pool()
i. pg_simple - no Pool()
j. asyncpg.pool - no Pool()
k. ctds - no Pool()

Does anyone have any ideas what the missing pool module could be?

Thanks in advance

Multiple insert statements using execute(multi=True) (no replies)

$
0
0
I have a string constructed with multiple insert statements and insert statement with values given in multiple-row syntax. Is it possible to specify multiple insert statements along with values given by multiple row syntax for execute(multi=true) in mysql-connector-python? For. e.g below is the string concatenated with the insert statements, first statement with multiple row values:

operation = 'INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9)(11,22,33),(44,55,66),(77,88,99);
INSERT INTO tb2_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
INSERT INTO tbl1_name (col1,col2) VALUES(col2*2,15);
INSERT INTO tbl1_name (col1,col2) VALUES(15,col1*2);
INSERT INTO tbl2_name (col1,col2) VALUES(col2*2,15);
INSERT INTO tbl2_name (col1,col2) VALUES(15,col1*2);'
for result in cursor.execute(operation, multi=True):
print reslut.row_count

Bulk insert query : executemany vs execute(multi = True) (no replies)

$
0
0
Which is more efficient executemany or execute(multi=True) for bulk insert query?

operation = 'INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9)
(11,22,33),(44,55,66)(77,88,99);
INSERT INTO tb2_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
INSERT INTO employees (first_name, hire_date) VALUES ('Jane',
'2005- 02-12'), ('Joe', '2006-05-23'), ('John', '2010-10-03')'

for result in cursor.execute(operation, multi=True):
print (result.rowcount)

or

data = [
('Jane', date(2005, 2, 12)),
('Joe', date(2006, 5, 23)),
('John', date(2010, 10, 3)),
]
stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s)"
cursor.executemany(stmt, data)

data2 = [
('Jane', date(2005, 2, 12)),
('Joe', date(2006, 5, 23)),
('John', date(2010, 10, 3)),
]
stmt1 = "INSERT INTO table1 (first_name, hire_date) VALUES (%s, %s)"
cursor.executemany(stmt1, data2)

mysql-connector-python for python3 installed - where? (no replies)

$
0
0
I run Linux Mint 18.3 based on Ubuntu16.04.1. I have started to use python3.6 which I installed (python 2.7 & 3.5 obviousli came with the distro Mint 18.3)
I have (via the community page) tried to install mysql-connector-python-cext-py3
The installer displays some directories which I guess are relevant directories from where to import mysql connector.
But none of these directories seem to contain the names that I suppose must be imported into the python script to connect to the database.
I have from the installer:
1)usr/lib/python3/dist-packages/_mysql_connector.cpython-35m-i386-linux-gnu-so.
2)usr/share/dic/mysql-connector-python-cext-py3/
I also have in my file system
3)usr/lib/python3/dist packages/mysql/connector
in 3) there is no .py module called connector, only one called connection.py.

Trying this:
#!/usr/lib/python3/disp-packages/mysql/connection
from __future__ import print_function

import mysql.connection
from mysql.connection import errorcode

Results in failure.
Traceback (most recent call last):
File "testsql.py", line 4, in <module>
import mysql.connection
ModuleNotFoundError: No module named 'mysql'

So, this construct requires a mysql mdule , byt I do not know where it can be found. Something may have gone wrong during installation.
Can you give me the necessary hints?

connector/python (no replies)

$
0
0
Does python connection to MySQL work at all? I have now undertaken an extensive study of the topic, and the closest I get is this file
/usr/lib/python3/dist-packages/_mysql_connector.cpython-35m-i386-linux-gnu.so

The archive manager shows that this file is contained in
mysql-connector-python-cext-py3_2.1.7-1ubuntu16.04_i386.deb

which is a file obtained from the connector/python download page

I saved it in /tmp and ran dpkg -i mysql-connector-python-cext-py3_2.1.7-1ubuntu16.04_i386.deb

The code example in the documentation chapter 5.1
#!/usr/lib/python/dist-packages (added by me)
import mysql.connector

results in:

File "testsql.py", line 9, in <module>
import mysql.connector
ModuleNotFoundError: No module named 'mysql'

I have bees searching a lot to find the mysql module, but it seems not to be present. At least not using the linux find command.
It seems to me that something must be very wrong here.
I am running; python3.6, Linux Mint 18.3 (based on Ubuntu 16.04) and
MySQL 5.7.21-0

Can't install connector-python for Python 3 on RHEL 6 (no replies)

$
0
0
I've been following the instructions at https://dev.mysql.com/doc/connector-python/en/connector-python-installation-source.html for installing from source on Unix systems. I have the mysql, mysql-devel, and mysql-server packages installed on the server as well. I need the c extensions, and that configuration option is what is causing the error (if I install it without the c extensions it installs fine). The command I issue is "python3.6 setup.py install --with-mysql-capi=/usr/lib64/mysql/mysql_config" but it just throws the following error:

running install
Installing MySQL C Extension
running build
running build_py
running build_ext
# Python architecture: 64-bit
# Python ARCH_64BIT: True
# Looking mysqlclient_lib at path: -rdynamic/lib-L/usr/lib64/mysql*
Traceback (most recent call last):
File "setup.py", line 64, in <module>
ext_modules=setupinfo.extensions,
File "/usr/lib64/python3.6/distutils/core.py", line 148, in setup
dist.run_commands()
File "/usr/lib64/python3.6/distutils/dist.py", line 955, in run_commands
self.run_command(cmd)
File "/usr/lib64/python3.6/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/mysql-connector-python-2.1.7/lib/cpy_distutils.py", line 665, in run
install.run(self)
File "/usr/lib64/python3.6/distutils/command/install.py", line 545, in run
self.run_command('build')
File "/usr/lib64/python3.6/distutils/cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "/usr/lib64/python3.6/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/usr/lib64/python3.6/distutils/command/build.py", line 135, in run
self.run_command(cmd_name)
File "/usr/lib64/python3.6/distutils/cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "/usr/lib64/python3.6/distutils/dist.py", line 973, in run_command
cmd_obj.ensure_finalized()
File "/usr/lib64/python3.6/distutils/cmd.py", line 107, in ensure_finalized
self.finalize_options()
File "/mysql-connector-python-2.1.7/lib/cpy_distutils.py", line 423, in finalize_options
self._finalize_connector_c(self.with_mysql_capi)
File "/mysql-connector-python-2.1.7/lib/cpy_distutils.py", line 374, in _finalize_connector_c
myc_info = get_mysql_config_info(mysql_config)
File "/mysql-connector-python-2.1.7/lib/cpy_distutils.py", line 226, in get_mysql_config_info
log.debug("# mysqlclient_lib: {0}".format(mysqlclient_libs[-1]))
IndexError: list index out of range

MySQL 8.0: Connector/Python 8.0 (no replies)


Windows: connector 8.0.11 does not read "option_files" (no replies)

$
0
0
Hi,

I've been having this problem for a while. The Python connector does not understand the "option_files" connection argument. I have the following situation:

I have a development environment and I sometimes want to drop every table in the dev DB and recreate. Because of my hosting provider I can not drop or add a "database from the command line. I wrote the script below to look for and drop the tables in the database though.

import os
import mysql.connector.django

DBI = mysql.connector.connect(
option_files=os.path.join(os.path.expanduser("~"), ".my.cnf"),
option_groups="membersdev"
)

cursorFind = DBI.cursor()
cursorDrop = DBI.cursor()

query = """
select TABLE_NAME
from information_schema.TABLES
where TABLE_SCHEMA = 'dev_devSite_org'
"""
cursorFind.execute(query)

query2 = """
drop table if exists %s
"""

for (tableName) in cursorFind:
print(tableName)
cursorDrop.execute(query2, tableName)

cursorDrop.close()
cursorFind.close()

DBI.close()

This script works fine on the linux dev machine. It fails on Windows. I get the stacktrace:

Traceback (most recent call last):
File "C:\Program Files\Python36\lib\site-packages\mysql\connector\connection_cext.py", line 176, in _open_connection
self._cmysql.connect(**cnx_kwargs)
_mysql_connector.MySQLInterfaceError: Can't connect to MySQL server on '127.0.0.1' (10061)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm 2017.3.2\helpers\pydev\pydevd.py", line 1664, in <module>
main()
File "C:\Program Files\JetBrains\PyCharm 2017.3.2\helpers\pydev\pydevd.py", line 1658, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm 2017.3.2\helpers\pydev\pydevd.py", line 1068, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm 2017.3.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/karres/PycharmProjects/CIAMembers/misc_scripts/db_delete.py", line 16, in <module>
option_groups="membersdev"
File "C:\Program Files\Python36\lib\site-packages\mysql\connector\__init__.py", line 148, in connect
return connect(**new_config)
File "C:\Program Files\Python36\lib\site-packages\mysql\connector\__init__.py", line 182, in connect
return CMySQLConnection(*args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\mysql\connector\connection_cext.py", line 78, in __init__
self.connect(**kwargs)
File "C:\Program Files\Python36\lib\site-packages\mysql\connector\abstracts.py", line 736, in connect
self._open_connection()
File "C:\Program Files\Python36\lib\site-packages\mysql\connector\connection_cext.py", line 179, in _open_connection
sqlstate=exc.sqlstate)
mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (10061)

It should not be trying to connect to localhost via networking because the config file says to use a socket:


[membersdev]
socket=MySQL
protocol=pipe
user=devsiteorg
password=********
database=dev_site_org

I know that the config file *works* from the windows commend line because I can start the mysql client in a command window and specify the default file. the "client" part of the config file is the same as the one above.

Connector 8.0.11 return binary keys??? (1 reply)

$
0
0
Here are 2 example results from queries performed using MYSQL connector 8.0...

Before 8.0.11:

{'Expiration': datetime.datetime(2018, 5, 9, 14, 30, 40), 'IdUser': 143, 'Id': 9999999, 'Token': 'KAJGHKJ8976976JKHLJKH'}

With 8.0.11:

{b'Expiration': datetime.datetime(2018, 5, 9, 14, 30, 40), 'IdUser': 143, 'Id': 9999999, 'Token': 'KAJGHKJ8976976JKHLJKH'}

As you can see, the key for datetime objects is no longer a normal string, but a bytes literal.

Because of this, all the record parsing functionality is now broken because datetime values are no longer found in the query results.

Please let me know if there is an easy fix to this issue.

Ordering a table in select statement by row creation/update time (no replies)

$
0
0
Hi all,

When I was using sqllite3, I was able to sort table contents by system attribute "rowid" like "SELECT username FROM personal ORDER BY rowid". This attribute lists rows by creation time automaticly. Is there the same attribute in Mysql? I do not want to add another column just for sorting table contents as "rowid" does.

Thanks in advance,
Semih.

Mysql throwing an error but not able to catch using except (no replies)

$
0
0
I was going through the docs for mysql connector and came across this.

https://dev.mysql.com/doc/connector-python/en/connector-python-example-ddl.html

This is a sample code which I am running. from future import print_function

import mysql.connector
from mysql.connector import errorcode

config = {
'user' : 'root',
'password' : 'root',
'host' : '127.0.0.1',
'raise_on_warnings' : True,
}
DB_NAME = 'testdbwhichdoesnotexist'
def createdatabase(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)

cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()

try:
cnx.database = DB_NAME
except mysql.connector.Error as err:
if err.errno == errorcode.ER_BAD_DB_ERROR:
createdatabase(cursor)
cnx.database = DB_NAME
else:
print(err)
exit(1)
but if I assign DB_NAME to something new. It is throwing a error, but it is not being handled by the except which should create that respective db.

The error I see is :

Traceback (most recent call last):
File "msq.py", line 52, in <module>
cnx.database = DB_NAME
File "/home/*****/.local/lib/python3.5/site-packages/mysql/connector/connection_cext.py",line 138, in database
self._cmysql.select_db(value)
_mysql_connector.MySQLInterfaceError: Unknown database 'testdbwhichdoesnotexist'
Where am I going wrong ? Why is the exception not being handled by the except block ?

accessing data in python application (no replies)

$
0
0
Ive successfully connected mysql to Visual studio with the 'MySQL for visual studio' and 'Connector/Python' add ons. I am able to see my database connection in the server explorer and open tables within the database. However i am struggling to be able to make the connection within my written code (i need to run algorithms on the data). My inital idea was to create a dataframe with all the data and run algorthims on that. I ran the following code:

engine=create_engine('mssql+pyodbc://'+servername+'/'+database)
conn=engine.connect()
metadata=MetaData(conn)
tbl=Table(tablename,metadata,autoload=True,schema='dbo')
sql=tbl.select()
result=conn.execute(sql)
df=pd.DataFrame(database=list(result),columns=result.keys())
conn.close()

and received an sqlalchemy interface error- data source name not found and no default driver specified.

I also tried:

engine=sqlalchemy.create_engine('mysql+mysqlconnector://Localhost(databasename)/Table/new_event_data')
the_frame=pd.read_sql_query("SELECT * FROM %s;" %new_event_data, engine)
the_frame=pd.read_sql_table(new_event_data, engine)

which resulted in an error of 'new_event_data' is not specified.

There seems to be an issue making the connection between my code and the data. The full path for the data from the mysql database which was imported into visual studio is : DataExplorer://Localhost(databasename)/Table/new_event_data

Any tips on getting the data into a suitable format to access in ML algorthims? eg dataframe etc. Many thanks.
Viewing all 387 articles
Browse latest View live


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