I am learning to use the MySQL Connector/Python. When I insert multiple rows together into the table using the code below, it shows an error. But it works when I insert only one row at at time.
Here's the python code I have written:
import mysql.connector as sql
mydb = sql.connect(host = "localhost", user = "root", passwd = "your_password", database = "testdb")
mycursor = mydb.cursor()
str = "insert into test (Name, Address) values (%s, %s)"
val = [
('Foster', 'Moonland'),
('Toblerone', 'Marstown'),
('Hershey', 'Neptunestadt'),
('Cadbury', 'Jupiter DC')
]
mycursor.execute(str, val)
mydb.commit()
This the error message:
Traceback (most recent call last):
File "C:\Users\shoun\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\conversion.py", line 183, in to_mysql
return getattr(self, "_{0}_to_mysql".format(type_name))(value)
AttributeError: 'MySQLConverter' object has no attribute '_tuple_to_mysql'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\shoun\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\cursor.py", line 432, in _process_params
res = [to_mysql(i) for i in res]
File "C:\Users\shoun\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\cursor.py", line 432, in <listcomp>
res = [to_mysql(i) for i in res]
File "C:\Users\shoun\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\conversion.py", line 186, in to_mysql
"MySQL type".format(type_name))
TypeError: Python 'tuple' cannot be converted to a MySQL type
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\coding\python\mysql_connector\connectSQL.py", line 24, in <module>
mycursor.execute(str, val)
File "C:\Users\shoun\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\cursor.py", line 557, in execute
psub = _ParamSubstitutor(self._process_params(params))
File "C:\Users\shoun\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\cursor.py", line 437, in _process_params
"Failed processing format-parameters; %s" % err)
mysql.connector.errors.ProgrammingError: Failed processing format-parameters; Python 'tuple' cannot be converted to a MySQL type
But if val is a single tuple, the code executes without producing any error.
Related
I was about to start using mongodb as my database project. I'm always stuck when want to pushing some data to it. I use mongodb atlas. This code below always resulting errors. I've following and learning about mongodb from online (like youtube, w3, etc)
import pymongo
from pymongo import MongoClient
url = "mongodb+srv://<username>:<password>#cluster0.oecqh.mongodb.net/test?retryWrites=true&w=majority"
cluster = MongoClient(url)
db = cluster["discord"]
collection = db["discord"]
push = {"name": "test", "value": "test"}
try:
collection.insert_one(push)
except Exception as e:
print(e)
The errors
Exception ignored in: <function Client.__del__ at 0x00000213C5D84940>
Traceback (most recent call last):
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\httpx\_client.py", line 1139, in __del__
self.close()
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\httpx\_client.py", line 1111, in close
self._transport.close()
AttributeError: 'Client' object has no attribute '_transport'
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
self.run()
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\dns\win32util.py", line 48, in run
self.info.domain = _config_domain(interface.DNSDomain)
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\dns\win32util.py", line 26, in _config_domain
if domain.startswith('.'):
AttributeError: 'NoneType' object has no attribute 'startswith'
Traceback (most recent call last):
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 89, in _resolve_uri
results = _resolve(
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 43, in _resolve
return resolver.resolve(*args, **kwargs)
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\dns\resolver.py", line 1193, in resolve
return get_default_resolver().resolve(qname, rdtype, rdclass, tcp, source,
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\dns\resolver.py", line 1063, in resolve
(nameserver, port, tcp, backoff) = resolution.next_nameserver()
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\dns\resolver.py", line 646, in next_nameserver
raise NoNameservers(request=self.request, errors=self.errors)
dns.resolver.NoNameservers: All nameservers failed to answer the query _mongodb._tcp.cluster0.oecqh.mongodb.net. IN SRV:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\chris\OneDrive\Documents\Programming\Python\tempCodeRunnerFile.py", line 5, in <module>
cluster = MongoClient(url)
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\mongo_client.py", line 704, in __init__
res = uri_parser.parse_uri(
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\uri_parser.py", line 542, in parse_uri
nodes = dns_resolver.get_hosts()
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 121, in get_hosts
_, nodes = self._get_srv_response_and_hosts(True)
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 101, in _get_srv_response_and_hosts
results = self._resolve_uri(encapsulate_errors)
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\pymongo\srv_resolver.py", line 97, in _resolve_uri
raise ConfigurationError(str(exc))
pymongo.errors.ConfigurationError: All nameservers failed to answer the query _mongodb._tcp.cluster0.oecqh.mongodb.net. IN SRV:
c.execute("SELECT * FROM addresses WHERE oid = " + record_id)
c.execute("DELETE from addresses WHERE oid = " + delete_box.get)
These are the two lines where the error is shown
I did read an answer here on stackoverflow but the error wasnt rectified.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Nampoothiri\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1884, in __call__
return self.func(*args)
File "C:\Users\Nampoothiri\OneDrive\Desktop\College\Python\EXPERIMENT 6\TKINTER.py", line 153, in delete
c.execute("DELETE from addresses WHERE oid = " + delete_box.get())
sqlite3.OperationalError: incomplete input
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Nampoothiri\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1884, in __call__
return self.func(*args)
File "C:\Users\Nampoothiri\OneDrive\Desktop\College\Python\EXPERIMENT 6\TKINTER.py", line 89, in edit
c.execute("SELECT * FROM addresses WHERE oid = " + record_id);
sqlite3.OperationalError: incomplete input
These are the errors that keep showing.
I am receiving "TypeError: bad argument type for built-in operation" error when calling cursor.columns from pyodbc, Traceback the issue to threading.py -> currentThread function...
I have installed my python environment on a new HP Z2 desktop PC running :
Win10 enterprise x64
Python 2.7.13 on win32
PyScripter 3.5.1.0 x86
and suddenly received a very strange error while trying to insert data into my database using pyodbc module.
My code -
class clsDataBaseWrapper():
def __init__(self,ServerAddress='WIGIG-703\SQLEXPRESS',DataBase='QCT_Python',dBEn=1):
if (dBEn) :
self.DataBase=DataBase
self.cnxn = pyodbc.connect("Driver={SQL Server}"+
"""
;Server={0};
Database={1};
Trusted_Connection=yes;""".format(ServerAddress,DataBase))
self.cursor = self.cnxn.cursor()
else : print "\n*** Be Aware - you are not writing data to the DataBase !!! ***"
def InsertData(self,Table,Data,dBEn):
if (dBEn) :
columns = self.cursor.columns(table=Table, schema='dbo').fetchall()
insertQuery = "insert into {0} values ({1})".format(Table, ','.join('?' * len(columns)))
try :
self.cursor.execute(insertQuery, Data)
self.cnxn.commit()
except Exception,e : print 'could not insert data into DB - ',e
else : pass
The error I receive -
C:\Python27\lib\threading.py:1151: RuntimeWarning: tp_compare didn't return -1 or -2 for exception
return _active[_get_ident()]
Traceback (most recent call last):
File "C:\Qpython\IsonM_TC2\Services_IsonM_TC2.py", line 335, in <module>
test.InsertData('PLL_CL_PN_PLL',[],1)
File "C:\Qpython\IsonM_TC2\Services_IsonM_TC2.py", line 87, in InsertData
columns = columns.fetchall()
File "C:\Qpython\IsonM_TC2\Services_IsonM_TC2.py", line 87, in InsertData
columns = columns.fetchall()
File "C:\Python27\lib\bdb.py", line 49, in trace_dispatch
return self.dispatch_line(frame)
File "C:\Python27\lib\bdb.py", line 67, in dispatch_line
self.user_line(frame)
File "<string>", line 126, in user_line
File "C:\Python27\lib\threading.py", line 1151, in currentThread
return _active[_get_ident()]
TypeError: bad argument type for built-in operation
This is very strange because it is working perfectly on other old PC I have running the same environment.
What do I miss here ? tried re-installing python, pyscripter ...
Inserting multiple MySQL records using Python
Error: Python 'tuple' cannot be converted to a MySQL type
ERROR CODE:
Traceback (most recent call last):
File "C:\Users\POM\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\conversion.py", line 181, in to_mysql
return getattr(self, "_{0}_to_mysql".format(type_name))(value)
AttributeError: 'MySQLConverter' object has no attribute '_tuple_to_mysql'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\POM\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 432, in _process_params
res = [to_mysql(i) for i in res]
File "C:\Users\POM\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 432, in <listcomp>
res = [to_mysql(i) for i in res]
File "C:\Users\POM\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\conversion.py", line 184, in to_mysql
"MySQL type".format(type_name))
TypeError: Python 'tuple' cannot be converted to a MySQL type
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "python_mysql_2.py", line 22, in <module>
my_cursor.execute(mike_placeholders,records_list)
File "C:\Users\POM\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 557, in execute
psub = _ParamSubstitutor(self._process_params(params))
File "C:\Users\POM\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 437, in _process_params
"Failed processing format-parameters; %s" % err)
mysql.connector.errors.ProgrammingError: Failed processing format-parameters; Python 'tuple' cannot be converted to a MySQL type
Python Code:
#import sql.connector
import mysql.connector
#Create connection, added db we created#
connection = mysql.connector.connect(
host='localhost',
user='root',
password='123',
database='testdb_1'
)
#Create cursor for the connection
my_cursor = connection.cursor()
#Create SQL statement with placeholders and put in variable
mike_placeholders="INSERT INTO users (name,email,age) VALUES (%s, %s, %s) "
#Create list (array) of records
records_list = [('Tim','Tim#tim.com',32), ('Mary','Mary#mary.com',40), ('Sam','Sam#sam.com',50), ('Fred','Fred#fred.com',22) ]
#Execute cursor, requires SQl statement variable, record variable
my_cursor.execute(mike_placeholders,records_list)
#Commit the connection to make the change on the database
connection.commit()
Ahhh, I used the wrong Python term.
I should have used executemany when working with a tuple.
my_cursor.executemany(mike_placeholders,records_list)
You can't pass a list to my_cursor.execute(), you need to iterate over the list:
for values in records_list:
my_cursor.execute(mike_placeholders, values)
Or you could repeat the (%s, %s, %s) multiple times and do it all in a single query by flattening the list of tuples.
mike_placeholders="INSERT INTO users (name,email,age) VALUES " + ", ".join(["(%s, %s, %s)"] * len(records_list))
my_cursor.execute(mike_placeholders, sum(records_list))
use my_cursor.executemany(mike_placeholders,records_list)
If you have multiple elements which are saved in a list or tuple then use,
cursor.executemany(query,list) or cursor.executemany(query,tuple)
You must use a for loop and INSERT item by item
for x in records_list:
my_cursor.execute(mike_placeholders, x)
With Python 3.6.2 and MySQL Connector 2.1.6 package on Windows 10, not calling the execute method of a database cursor, or calling it on a non SELECT statement (CREATE, DROP, ALTER, INSERT, DELETE, UPDATE, etc.) yields the following results:
>>> import mysql.connector
>>> session = mysql.connector.connect(user = "root", database = "mysql")
>>> cursor = session.cursor()
>>> cursor.fetchone()
>>> cursor.fetchmany()
[]
>>> cursor.fetchall()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Maggyero\AppData\Local\Programs\Python\Python36-32\lib\site-packages\mysql\connector\cursor.py", line 891, in fetchall
raise errors.InterfaceError("No result set to fetch from.")
mysql.connector.errors.InterfaceError: No result set to fetch from.
>>> cursor.execute("CREATE TABLE test (x INTEGER)")
>>> cursor.fetchone()
>>> cursor.fetchmany()
[]
>>> cursor.fetchall()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Maggyero\AppData\Local\Programs\Python\Python36-32\lib\site-packages\mysql\connector\cursor.py", line 891, in fetchall
raise errors.InterfaceError("No result set to fetch from.")
mysql.connector.errors.InterfaceError: No result set to fetch from.
PEP 249 explicitly states for the fetchone, fetchmany and fetchall methods:
An Error (or subclass) exception is raised if the previous call to .execute*() did not produce any result set or no call was issued yet.
So why don't fetchone and fetchmany raise an exception like fetchall?
I filed a bug report on bugs.mysql.com and the bug has been fixed in MySQL Connector/Python 8.0.23.