Converting from Tuple to List to modify in Python - python

I am querying a Oracle database and need some special handling around one column of data that is a clob. I can read in the clobe with .read(). I'd like to write the actual value back to my array. It's a tuple so I must convert to a list, write the value, then convert back to tuple. I am getting the error message: TypeError: 'tuple' object does not support item assignment
My Code:
import cx_Oracle
# USE THIS CONNECTION STRING FOR PRODUCTION
production_username = 'username'
production_password = 'password'
con_string = '%s/%s#hostname:port/orcl' % (production_username, production_password)
con = cx_Oracle.connect(con_string)
cursor = con.cursor()
querystring = ("Select ID, Description from Table")
cursor.execute(querystring)
data = cursor.fetchall()
for currentrow in range(1, len(data)):
description= data[currentrow][1].read()
data = list(data)
data[currentrow][1] = description
data = tuple(data)
con.close()
print data

Try this way
for currentrow in data :
description= currentrow[1].read()
tupled_data= tuple([currentrow[0],description])
print tupled_data

Related

im facing type errorr object of type cx_oracle has no len()

[![enter image description here][1]][1]hi im facing type error cx+_orcle has no len() can you please help
query1="SELECT B.RMT_SITE_NM, A.CO_APPL_PRFL_ID, A.PRFL_ID FROM MIGRATION_TRACKING A, T_SFT_INIT_PRTCL B WHERE A.PRFL_ID=B.INIT_PRTCL_ID AND A.STATUS='Scheduled' AND A.PHASE='Phase 1' AND A.WAVE='Wave 1'"
cursor = connection()
ans = cursor.execute(query1)
if ans:
for rows in range(len(ans)):
name = str(ans[rows][0])
co_id_table = cursor.execute(query2,(name))
if co_id_table:
co_id = co_id_table[0][17]
data = cursor.execute(query3,(co_id))
data = data[0]
rndm_id = generate_id() ```
[1]: https://i.stack.imgur.com/YsnMs.jpg
[2]: https://i.stack.imgur.com/bttB1.jpg
This is the incorrect way of iterating over rows. You should instead do this:
for row in cursor.execute(query1):
name = str(row[0])
...
If you prefer to get all of the rows up front (since you are going to use the same cursor to execute other queries), then you can do this:
cursor.execute(query1)
rows = cursor.fetchall()
The value returned from cursor.execute() when the statement executed is a query is simply the cursor itself. Since the cursor implements the iteration protocol, you can also do this:
cursor.execute(query1)
rows = list(cursor)

Python: TypeError: Unsupported format string passed to NoneType.__format__

I have a program when it currently reads from a database, which can be found here. I have users choose a specific record they want to display so the SQL command will execute that record. Now I have a table that currently displays some records that do not include any NULL or empty strings. If it does have NULL or empty strings, it gives me an error and the program does not display the records. I figured that is where the NoneType error is mostly coming from. I'm not sure how to fix that. How can I make sure it also counts the Null or empty strings? Hopefully, that will fix the error.
If you were to try and test the DB, tables like Customers don't display because it has null values.
Here is the Traceback error:
line '..', in read_display(record)
line = format_.format(*rec)
TypeError: unsupported format string passed to NoneType.__format__
This is what my code looks like:
import sqlite3
def read_display(record):
database = 'data.db'
connection = sqlite3.connect(database)
c = connection.cursor()
sql = "SELECT * FROM {0}".format(record)
cursor.execute(sql)
conn.commit()
results = cursor.fetchall()
header = tuple(i[0] for i in c.description)
width = max((len(str(x)) for d in data for x in d))
data = [header] + results
config = [{'width': 0} for _ in range(len(data[0]))]
for rec in data:
for c, value in enumerate(rec):
config[c]['width'] = max(config[c]['width'], len(str(value)))
format_ = []
for f in config:
format_.append('{:<' + str(f['width']) + '}')
format_ = ' | '.join(format_)
for rec in data:
line = format_.format(*rec)
print(line)
You have error in
line = format_.format(*rec)
and you can get the same error with
'{:s}'.format(None)
so it seems rec has None on the list.
You would have to convert it to string with str(None)
You can use str() with all elements in rec to make sure:
rec = [str(x) for x in rec]
So code should be
for rec in data:
rec = [str(x) for x in rec]
line = format_.format(*rec)

Converting data from sqlite3 database into an array format

I have a problem where I am trying to call a specific field from the data recovered by the self.results variable from the sqlite3 login database, although I am unable to do this as I believe that the fetched data is not in an array format and therefore the system is unable to use that field, I got rid of all the " ' ", "(", ")" but I do not know what to do now to convert this text file into an array so that a field can be fetched and printed.
Could you help me?
while True:
username = self.usernameEntry.get()
password = self.passwordEntry.get()
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
findUser = ("SELECT * FROM students WHERE CardNumberID = ? AND Password = ?")
cursor.execute(findUser, [(username), (password)])
self.results = cursor.fetchone()
fetchedResults = str(self.results)
fetchedResults = fetchedResults.replace('(', '')
fetchedResults = fetchedResults.replace(')', '')
fetchedResults = fetchedResults.replace("'", '')
fetchedResults.split(',')
print(fetchedResults[2])
print(self.results)
Here are the results that I get:
The results are in an "array" format, but you then explicitly convert the whole thing to a string. Don't do that.

Data type conversion via sql query

I have problem with data type conversion.
Using django and pypyodbc lib I'm trying to recieive data from oracle DB (external) and save it into local app DB.
import pypyodbc
def get_data(request):
conn = pypyodbc.connect("DSN=...")
cursor = conn.cursor()
cursor.execute("SELECT value FROM table")
data = cursor.fetchall()
for row in data:
d = External_Data(first_val = row[0])
d.save()
The output from value is "0,2" and I've received error message:
could not convert string to float: b',02'
When I changed sql statement to:
SELECT cast(value as numeric(10,2) from table)
I received error message:
[<class 'decimal.ConversionSyntax'>]
How to change that data to get float data and save it. I use DecimalField(max_digits=10, decimal_places=2) as model field.
I think this problem comes with implicit type change.
when you get data from your get_data function, row[0] var in for loop is seemed like Bytes variable.
So First of all, I recommend to check row[0]'s data type with print(type(row[0])).
If result is Bytes, you can do like this:
import pypyodbc
def get_data(request):
conn = pypyodbc.connect("DSN=...")
cursor = conn.cursor()
cursor.execute("SELECT value FROM table")
data = cursor.fetchall()
for row in data:
data = float(str(row[0]).replace(',','.'))
d = External_Data(first_val=data)
d.save()

TypeError: Can't convert 'list' object to str implicitly SQLite3 Retrieving Data

def course_id(enrolment_id):
con = None
try:
con = lite.connect('C:/Users/Ethan/Desktop/SAT/SiemensAssessmentTool.db')
with con:
cur = con.cursor()
cur.execute("SELECT course_id FROM Enrolment WHERE enrolment_id = '"+ enrolment_id+ "';")
rows = cur.fetchall()
courseids=[]
for row in (rows):
courseids = row
return courseids
finally:
if con:
con.close()
What I'm trying to do with this code is retrieve a number of integers, as I will be connecting it to another function to find other data from the database. The error I get is when I connect it with other function:
def course_name(course_id):
con = None
try:
con = lite.connect('C:/Users/Ethan/Desktop/SAT/SiemensAssessmentTool.db')
with con:
cur = con.cursor()
cur.execute("SELECT course_name FROM Course WHERE course_id = '"+ course_id+ "';")
rows = cur.fetchall()
return rows
finally:
if con:
con.close()
And I get this error:
cur.execute("SELECT course_id FROM Enrolment WHERE enrolment_id = '"+ enrolment_id+ "';")
TypeError: Can't convert 'list' object to str implicitly
I'm guessing it has something to do with the course_id function, but I am not sure.. Thank you in advance
TypeError: Can't convert 'list' object to str implicitly
Clearly, the problem is that enrolment_id is a list, check what do you pass into the course_id() as an argument.
As a side note, you should not construct your query via string concatenation - this leads to problems with type conversions and makes your code vulnerable to SQL injections - parameterize the query instead:
cur.execute("SELECT course_id FROM Enrolment WHERE enrolment_id = ?", (enrolment_id, ))
There is also a problem in how you get the result of the query. Assuming you want a single course ID from the database, use fetchone():
courseid = cursor.fetchone()[0]
return courseid

Categories