Decode an encoded value from DB using Python - python-3.x

I encoded a value from input file and inserted into Sqlite DB
cur.execute('''INSERT INTO Locations (address, geodata)
VALUES ( ?, ? )''', (memoryview(address.encode()), memoryview(data.encode()) ) )
Now I'm trying to decode it but I'm getting
Traceback (most recent call last):
File "return.py", line 9, in
print(c.decode('utf-8'))
AttributeError: 'tuple' object has no attribute 'decode'
My code looks like this:
import sqlite3
conn = sqlite3.connect('geodata.sqlite')
cur = conn.cursor()
cur.execute('SELECT address FROM Locations')
for c in cur:
print(c.decode('utf-8'))

Regardless of how many columns are selected, rows are returned as tuples. You would get the first element of the tuple the usual way.

Related

Python dataframe insert into Azure SQL

I would like to insert multiple records from pandas dataframe into MS Azure table via python:
lst = [
('111', 'AA', 'AAA'),
('222', 'BB', 'BBB'),
('333', 'CC', 'CCC')
]
cursor = conn.cursor()
cursor.fast_executemany = True
SQLCommand = ("INSERT INTO [dbo].[ServiceRequestCollection_tmp] (ObjectID,BuyerMainContactPartyID,BuyerMainContactPartyName) VALUES (?,?,?);")
cursor.execute(SQLCommand, lst)
cursor.commit()
Unfortunately, system generates the following error. Can I kindly ask you to help me
pyodbc.ProgrammingError: ("A TVP's rows must all be the same size.", 'HY000')
The above exception was the direct cause of the following exception:
SystemError: <built-in function utf_16_le_encode> returned a result with an error set
The above exception was the direct cause of the following exception:
SystemError: encoding with 'utf-16le' codec failed (SystemError: <built-in function utf_16_le_encode> returned a result with an error set)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:/Users/103925alf1/PycharmProjects/p10/p11.py", line 35, in <module>
cursor.execute(SQLCommand, lst)
SystemError: <class 'pyodbc.Error'> returned a result with an error set
Process finished with exit code 1
You can directly set cursor.fast_executemany = False.
Also, you can upgrade to pyodbc 4.0.24 (or newer) and use setinputsizes to specify the parameter type, etc..
sql = "INSERT INTO #issue295 (txt, dec) VALUES (?, ?)"
params = [('Ώπα', 3.141)]
# explicitly set parameter type/size/precision
crsr.setinputsizes([(pyodbc.SQL_WVARCHAR, 50, 0), (pyodbc.SQL_DECIMAL, 18, 4)])
crsr.fast_executemany = True
crsr.executemany(sql, params)
For more details, you could refer to this wiki.

TypeError: not all arguments converted during string formatting in python connecting with postgresql

It seems like all no error in the code but no idea why I'm getting this.
I was creating a simple GUI app which store user details to a database(postgresql) and also they will be able to search for entries in database. This particular error ocures in this search() function so I haven't added the rest of the code. If necessary I can add them.
Hope I will get some solutions from this community.
def search(id):
conn = psycopg2.connect(dbname="postgres",user="postgres",password="1018",host="localhost",port="5432")
mycursor = conn.cursor()
query = '''select * from demotab where id=%s '''
mycursor.execute(query, (id))
row = mycursor.fetchone()
print(row)
conn.commit()
conn.close()
Getting this error below
Exception in Tkinter callback
Traceback (most recent call last):
File "c:\programdata\anaconda3\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "appwithDB.py", line 51, in <lambda>
search_button = Button(newframe, text="Search", command=lambda : search(entry_search.get()))
File "appwithDB.py", line 71, in search
mycursor.execute(query, (id))
TypeError: not all arguments converted during string formatting
The second argument to mycursor.execute must be an iterable containing the values to insert in the query
You can use a list: mycursor.execute(query, [id])
or a one-element tuple: mycursor.execute(query, (id,))
Notice the comma. (id) is the same than id. In python, the comma is making the tuple, not the parenthesis.

Updating column in database with new values from pandas dataframe

I am attempting to update a column on an oracle database with new values which have been calculated and inputted into a pandas dataframe. The table name in the database is protein_info and the column I want to update is pct. I'm getting the following error when I run my code:
Traceback (most recent call last):
File "./update_nsaf.py", line 81, in
df.to_sql(protein_info, engine, index=False, if_exists='replace')
AttributeError: type object 'protein_info' has no attribute 'lower'
df = df[['id', 'pct']]
engine=create_engine('oracle://scott:tiger#localhost:5432/mydatabase', echo=False)
connect = engine.raw_connection()
df.to_sql(protein_info, engine, index=False, if_exists='replace')
sql = """
UPDATE protein_info
SET protein_info.pct = pct
FROM protein_info
WHERE protein_info.id = id
"""
connect.execute(sql)
connect.close()

Itertuples() in Tkinter function reveals an AttributeError: 'tuple' object has no attribute 'A'

Within a Tkinter function, I need to create the list named: 'value' extracting every 10 rows the value of dataframe column named: df['A'].
The following for-loop works perfectly out of a Tkinter function:
value = []; i = 0
for row in df.itertuples():
i = 1 + i
if i == 10:
value_app = row.A
value.append(value_app)
i=0
However within Tkinter function I have the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Users/anaconda/lib/python3.6/tkinter/__init__.py", line 1699, in __call__
return self.func(*args)
File "<ipython-input-1-38aed24ba6fc>", line 4174, in start
dfcx = self.mg(a,b,c,d,e)
File "<ipython-input-1-38aed24ba6fc>", line 4093, in mg
value_app = r.A
AttributeError: 'tuple' object has no attribute 'A'
A similar for-loop structure is running in another part of the same Tkinter function and is executed without errors.
If the column A is your first column you can do :
value_app = row[0]
I had the same problem and I think that it only sees it as regular arrays

Executing an insert query on each row in results: psycopg2.ProgrammingError: no results to fetch

What dumb thing am I missing here:
>>> cur.execute("select id from tracks")
>>> for row in cur:
... story = random.choice(fortunes) + random.choice(fortunes)
... cur.execute("update tracks set story=%s where id=%s", (story, row[0]))
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
psycopg2.ProgrammingError: no results to fetch
But there seem to be results:
>>> cur.execute("select id from tracks")
>>> for row in cur:
... print(row)
...
(8,)
(45,)
(12,)
(64,)
(1,)
(6,)
Looks like psycopg2 doesn't allow interleaved queries (although PostgreSQL can do it, on the back end). If the initial query isn't huge, the simplest solution would be to coalesce the results into a list - just change from row in cur: to from row in cur.fetchall(): and you should be right.

Resources