1241, 'Operand should contain 1 column(s)' when saving - python

I am trying to save some items to mysql with python and keep getting this error
I have connected to the db and then do a query on table1 and then later am trying to save to Resturants like this
cursor.execute("SELECT * FROM `table1`")
#do some stuff
cursor.execute("INSERT INTO Resturants (School,Resturant_Name,Phone,Street,City, State,Postal_Code,Country,Lat,Lng, Rating,Review_Count,Mobile_Url,Url) VALUES (%s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s,%s,%s)", (SCHOOL,bus_name,bus_phone,bus_address,bus_city, bus_state,bus_post,bus_country,bus_lat,bus_lng, bus_rating,bus_rating_count,bus_mobile_url,bus_url))
here is error
File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 174, in execute
File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
_mysql_exceptions.OperationalError: (1241, 'Operand should contain 1 column(s)')
And then I get the error on the INSERT line why?

Related

Python and SQL Server - _pymssql.ProgrammingError: (208, b"Invalid object name X. DB-Lib error message 20018, severity 16 ..)

I want to fetch data from a MSSQL Server (Microsoft SQL Server 2017) via Python (3.8.6) and the pymssql library (2.2.7).
The tables are in the dbo Schema of database A, the default database of the user is master.
By using the following code, I am able to fetch data from most of the tables:
import pymssql
# Connect to the database - dont mind the fake server, pw and other creds, database='A'
conn = pymssql.connect(
server='localhost',
user='sa',
password='1234',
database='A',
port=8888
)
# Create a cursor
cursor = conn.cursor()
# Execute a SELECT statement++++
c = cursor.execute("SELECT TOP 10 * FROM dbo.KHKBookings")
results = cursor.fetchall()
# Iterate over the results and print each row
for row in results:
print(row)
# Close the cursor and connection
cursor.close()
conn.close()
While it works for the example table KHKBookings, it does not for another one called icZGBookings, which is in the same database and also in dbo schema. I get the following error:
Traceback (most recent call last): File "src\pymssql_pymssql.pyx",
line 459, in pymssql._pymssql.Cursor.execute File
"src\pymssql_mssql.pyx", line 1087, in
pymssql._mssql.MSSQLConnection.execute_query File
"src\pymssql_mssql.pyx", line 1118, in
pymssql._mssql.MSSQLConnection.execute_query File
"src\pymssql_mssql.pyx", line 1251, in
pymssql._mssql.MSSQLConnection.format_and_run_query File
"src\pymssql_mssql.pyx", line 1789, in
pymssql._mssql.check_cancel_and_raise File "src\pymssql_mssql.pyx",
line 1835, in pymssql._mssql.raise_MSSQLDatabaseException
pymssql._mssql.MSSQLDatabaseException: (208, b"Invalid object name
'dbo.icZGBookings'.DB-Lib error message 20018, severity 16:\nGeneral
SQL Server error: Check messages from the SQL Server\n")
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "", line 1, in
File "src\pymssql_pymssql.pyx", line 476, in
pymssql._pymssql.Cursor.execute pymssql._pymssql.ProgrammingError:
(208, b"Invalid object name 'dbo.icZGBookings'.DB-Lib error message
20018, severity 16:\nGeneral SQL Server error: Check messages from the
SQL Server\n")
So we are not finding the table, I can also make up a table and get the same error.
Adding the Database to the query didnt help either:
SELECT TOP 10 * FROM A.dbo.icZGBookings
But why is that so? I cant figure it out, because the table icZGBookings exists.
I can see and query it with the same user sa in MSSQL Server Management Studio in the database A and schema dbo.
I even altered the default database for that user from master to A, but that didnt help either.
We should not need to do that anyway because we specify the database we connect to in the beginning.
The master database dbo schema is empty anyway and should have not worked for the other tables too.
So, why cant I query it via Python?
I compared the values of the two tables with the following query:
SELECT *
FROM sys.tables AS t
INNER JOIN sys.partitions AS p
ON t.object_id = p.object_id
WHERE t.name in ('KHKBookings', 'icZGBookings')
The values are not different besides the object_ids, index_ids, and dates of course.
Any idea?
Thank you in advance!

updating columns in sql DB using pymssql

I am trying to update all rows of the specific column in MSSQL database using pymssql. But I encountered with this error:
" Traceback (most recent call last):
File "src\pymssql_pymssql.pyx", line 460, in pymssql._pymssql.Cursor.execute
File "src\pymssql_mssql.pyx", line 1104, in pymssql._mssql.MSSQLConnection.execute_query
File "src\pymssql_mssql.pyx", line 1135, in pymssql._mssql.MSSQLConnection.execute_query
File "src\pymssql_mssql.pyx", line 1268, in pymssql._mssql.MSSQLConnection.format_and_run_query
File "src\pymssql_mssql.pyx", line 1806, in pymssql._mssql.check_cancel_and_raise
File "src\pymssql_mssql.pyx", line 1852, in pymssql._mssql.raise_MSSQLDatabaseException
pymssql._mssql.MSSQLDatabaseException: (102, b"Incorrect syntax near ','.DB-Lib error message 20018, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n") "
Here is my code:
params = [tuple(x) for x in all_list]
# print(params)
query = """UPDATE dbo.MYTABLE SET KeyWords=%s WHERE KeyWords=%s"""
for i in params:
val = ("NULL", i)
cursor.execute(query, val)
conn.commit()
print(cursor.rowcount)
Params variable is a list of tuples that are going to be the new values of my column. In the column, all values are filled with NULL and I want to update with the Params variable.
Any suggestion?
Thank you for help, in advance.

Load csv data into MySQL Python

I am trying to load csv data into a mysql table in python:
import csv
import MySQLdb
mydb = MySQLdb.connect(host='localhost', user='xuanyue', passwd='txn-data', db='eversafe_ml_dev')
cursor = mydb.cursor()
csv_data = csv.reader(file('txns.csv'))
for row in csv_data:
cursor.execute("INSERT INTO txn(UserID, AccountID, TransactionDate, Amount, Description, SimpleDescription, TransactionState, TransactionType, CategoryID, AcctCategoryID, CheckNum, City)"
"VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", row)
mydb.commit()
cursor.close()
The output is:
File "load_data.py", line 10, in <module>
"VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", row)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "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 'ription, TransactionState, TransactionType, CategoryID, AcctCategoryID, CheckNum' at line 1")
I don't understand in my csv file, are the data fields all strings even if it contains transaction date, amount and etc.?
Or should I use numbers, datetime and etc in VALUES( )?

Lost connection to MySQL server during Python connection

Relatively new to Python and MySQL, but I'm performing a simple query of a DB in a dev environment using the MySQL Python Connector. I've created a buffered cursor to return results as dictionaries. When I perform the simple query:
family_query = ("SELECT * FROM family as FF")
...I get a list of errors, all around this idea of error 2013: Lost Connection to MySQL server.
>python "FitMatch v1.5.py"
Traceback (most recent call last):
File "FitMatch v1.5.py", line 505, in <module>
fit_match_cursor.execute(fit_family_query, () )
File "C:\Python34\lib\site-packages\mysql\connector\cursor.py", line 507, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Python34\lib\site-packages\mysql\connector\cursor.py", line 421, in _handle_result
self._handle_resultset()
File "C:\Python34\lib\site-packages\mysql\connector\cursor.py", line 895, in _handle_resultset
(self._rows, eof) = self._connection.get_rows()
File "C:\Python34\lib\site-packages\mysql\connector\connection.py", line 671, in get_rows
rows = self._protocol.read_text_result(self._socket, count)
File "C:\Python34\lib\site-packages\mysql\connector\protocol.py", line 309, in read_text_result
packet = sock.recv()
File "C:\Python34\lib\site-packages\mysql\connector\network.py", line 226, in recv_plain
raise errors.InterfaceError(errno=2013)
mysql.connector.errors.InterfaceError: 2013: Lost connection to MySQL server during query
I've tried increasing my connection_timeout to well over 10,000 (as I read on other stack overflow posts that could be the issue) but it had no effect.
Any ideas what could be causing the "Lost connection to MySQL server" error?
As a print of nested query result I face this problem
my Python query would fail with the error described in the question after returning just a subset of results.
As my way you Switched to PyMySQL and things work as you like
PyMySQL Link
My Sample Code For printing data
import pymysql
connection = pymysql.connect(user='XYZ', passwd='XYZ',host='XYZ',database='XYZ')
cursor = connection.cursor()
query = ("YOUR_QUERY")
cursor.execute(query)
for item in cursor:
print item
If any problem with this answer must comment me....:)

Adding url to mysql row in python

I am trying to add a url to a text row in mysql using python and the MySQLdb library, but when I run my code it says there is an error in my sql syntax. Can you tell me what im doing wrong?
Here is my code:
import MySQLdb as mdb
connection = mdb.connect("Localhost", "root", "", "db")
cursor = connection.cursor()
url = mdb.escape_string("http://www.google.com")
cursor.execute("""INSERT INTO index(url) VALUES(%s)""", (url,))
Here is the error:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 551, in __bootstrap_inner
self.run()
File "E:\prospector\webworker.py", line 77, in run
cursor.execute("INSERT INTO index(url) VALUES('%s')", (url_t,))
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: (1064, "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 'index(url) VALUES('http://www.google.com/')' at line 1")
I was able to replicate your problem like this:
mysql> create table `index` (url varchar(50));
Query OK, 0 rows affected (0.05 sec)
mysql> insert into index(url) values ('http://www.google.com');
ERROR 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 'index(url) values ('http://www.google.com')' at line 1
mysql> insert into `index`(url) values ('http://www.google.com');
Query OK, 1 row affected (0.00 sec)
index is a keyword in MySQL. Your life will be easier if you do not use it as a table name.
However, if you really want to, you can use it, but then you have to quote it:
cursor.execute("""INSERT INTO `index`(url) VALUES(%s)""", (url,))
PS: No need to call
url = mdb.escape_string("http://www.google.com")
MySQLdb will do that automatically for you when you call
cursor.execute("""INSERT INTO index(url) VALUES(%s)""", (url,))
In fact, since cursor.execute calls mdb.escape_string for you, doing it yourself could cause undesired values to be inserted into the database depending on the value of url:
In [105]: MySQLdb.escape_string("That's all folks")
Out[105]: "That\\'s all folks"
In [106]: MySQLdb.escape_string(MySQLdb.escape_string("That's all folks"))
Out[106]: "That\\\\\\'s all folks"

Categories

Resources