How to get rid of a comma? - python

import sqlite3
conn = sqlite3.connect('contacten.db')
c = conn.cursor()
#c.execute("""CREATE TABLE mail (
# mail text
# )""")
#c.execute("INSERT INTO mail VALUES ('test#gmail.com')")
conn.commit()
c.execute("SELECT * FROM mail")
print(c.fetchall())
conn.commit()
conn.close()
This is the code I've made but as a result, I get:
[('test#gmail.com',), ('test1#gmail.com',), ('test2#gmail.com',)]
But in this array I have a comma too much. ,), like this. does anyone of you know how to get rid of this extra comma?

The commas are there for a good reason, your result is a list of tuples; this is a consequence of how sqlite represents the result set, the data itself doesn't contain commas:
result = c.fetchall()
print(result)
=> [('test#gmail.com',), ('test1#gmail.com',), ('test2#gmail.com',)]
That's because each row can have more than one field. In your case you only have one field, but Python can't just remove the comma, because if we did you'd end up with a list of elements between brackets, not a list of tuples (see here to understand why).
Of course, if you're certain that the result will only have one field per row, you can simply get rid of the tuples by extracting the one (and only) field from each row at the moment of printing the result:
result = c.fetchall()
print([f[0] for f in result])
=> ['test#gmail.com', 'test1#gmail.com', 'test2#gmail.com']

Using python zip:
>>> emails = [('test#gmail.com',), ('test1#gmail.com',), ('test2#gmail.com',)]
>>> emails, = zip(*emails)
>>> type(emails)
<type 'tuple'>
>>> emails
('test#gmail.com', 'test1#gmail.com', 'test2#gmail.com')
>>> list(emails)
['test#gmail.com', 'test1#gmail.com', 'test2#gmail.com']

import sqlite3
conn = sqlite3.connect('contacten.db')
c = conn.cursor()
#c.execute("""CREATE TABLE mail (
# mail text
# )""")
#c.execute("INSERT INTO mail VALUES ('test#gmail.com')")
#c.execute("INSERT INTO mail VALUES ('test1#gmail.com')")
#c.execute("INSERT INTO mail VALUES ('test2#gmail.com')")
conn.commit()
c.execute("SELECT * FROM mail")
#print(c.fetchall())
for item in c.fetchall():
print item[0]
conn.commit()
conn.close()

Related

Retrieving text from sqlite without string formatting for comparison

Saving a string into a sqlite table, retrieving it again and comparing it to the original requires some filters to work and i dont know why exactly.
tl;dr
How can i retrieve string Data from the SQLITE DB without requiring Filter Nr 3 as its dangerous for more complex strings ?
import sqlite3
RAWSTRING = 'This is a DB Teststing'
# create database and table
currentdb = sqlite3.connect('test.db')
currentdb.execute('''CREATE TABLE tickertable (teststring text)''')
# enter RAWSTRING into databasse
currentdb.execute('''INSERT INTO tickertable VALUES(?);''', (RAWSTRING,))
# get RAWSTRING from database
cursorObj = currentdb.cursor()
cursorObj.execute('SELECT * FROM tickertable')
DB_RAWSTRING = cursorObj.fetchall()
currentdb.commit()
currentdb.close()
# Prints This is a DB Teststing
print('originalstring : ', RAWSTRING)
# Prints [('This is a DB Teststing',)]
print('retrieved from DB: ', DB_RAWSTRING)
# Get first entry from List because fetchall gives a list
FILTER1_DB_RAWSTRING = DB_RAWSTRING[0]
# Convert the Listelement to String because its still a listelement and comparing fails to string
FILTER2_DB_RAWSTRING = str(FILTER1_DB_RAWSTRING)
# Remove annoying db extra characters and i dont know why they exist anyway
FILTER3_DB_RAWSTRING = FILTER2_DB_RAWSTRING.replace("'", "").replace("(", "").replace(")", "").replace(",", "")
if RAWSTRING == FILTER3_DB_RAWSTRING:
print('Strings are the same as they should')
else:
print('String are not the same because of db weirdness')
So here's your problem: fetchall returns a list of tuples. This means that casting them to a string puts pesky parenthesis around each row and commas between each element of each row. If you'd like to retrieve the raw information from each column, that can be done by indexing the tuples:
entries = cursorObj.fetchall()
first_row = entries[0]
first_item = first_row[0]
print(first_item)
This ought to print just the content of the first row and column in the DB. If not, let me know!
David

How to remove extra comma in cur.fetchall()

I tried to output all values in a column in mysql however, it also outputs extra comma in the end.
def numbers():
db = getDB();
cur = db.cursor()
sql = "SELECT mobile_number FROM names"
cur.execute(sql)
result = cur.fetchall()
for x in result:
print(x)
It looks like this in shell:
(0123456789,)
(9876543210,)
a couple more options:
# validate that the results contain exactly one column
for [x] in result:
print(x)
and
# using argument unpacking
for x in result:
print(*x)
Basically as Ben's comment says the comma doesn't technically exist, it is there because it is a tuple.
but is you still want to remove it try this:
rows=[i[0] for i in rows]

Query regarding python database programming

I am using the below code to delete a row from sqlite table.
def deleteFromTable(item):
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("DELETE FROM store WHERE item=?", (item,))
conn.commit()
conn.close()
Why do i need to use comma after item (item,) while passing the argument?
('String') evaluates into string, but ('string',) evaluates into tuple. that's why you need comma.

Using Python see if Table exists

I have to connect to an Oracle database and see if a table exists. While I can get a list of the tables, I'm having trouble seeing if the table I'm looking for is in the list. Some tables have associated table which I'll have to join on, some do not, thus I have to check.
What is in my list: ('NYSDOH_CI_EI_HOSPITAL',)
sql = "SELECT table_name FROM all_tables"
cur.execute(sql)
searchstr = 'NYSDOH_CI_EI_HOSPITAL'
p = re.compile(searchstr)
#create data array to load in SQL results in.
ciDataSet = []
cxRows = cur.fetchall()
for i in cxRows:
#print i # list of tables
if p.match(str(i)):
print i
It doesn't find it, even if I use a wildcard.
fetchall() returns a list of tuples.
So when you do
for i in cxRows:
'i' is of type tuple. In your case, this tuple will have only single value. You can access it using i[0] and match it with p.
Currently you are converting a tuple to string so regular expression will not match.
Corrected code:
sql = "SELECT table_name FROM all_tables"
cur.execute(sql)
searchstr = 'NYSDOH_CI_EI_HOSPITAL'
p = re.compile(searchstr)
#create data array to load in SQL results in.
ciDataSet = []
cxRows = cur.fetchall()
for i in cxRows:
#print i # list of tables
if p.match(str(i[0])):
print i
To improve on the syntax of #vaichidrewar, you could simplify the fetch loop to:
for tabname, in cur:
if p.match(str(tabname)):
print(tabname)
But it's going to be more efficient to do the reg exp matching in the query:
sql = "select table_name from all_tables where regexp_like(table_name, :tn, 'i')"
searchstr = 'EMP'
cur.execute(sql, (searchstr,))
for tabname, in cur:
print(tabname)
The 'i' option does a case-insensitive match. You can adjust the regexp as you like.

This code is writing only one row in DB?

This code is writing only one row in DB
I find no error in this code . . .
But why is this not inserting more than the first row ?
def transremovechars():
cur.execute('drop table transforms')
char_cfg = config.get('Transform_Variables', 'Chars_to_be_removed') #Reads all the special chars to be removed from specialchars.txt#
cur.execute('select * from originallist')
for row in cur: #Applies transformation to remove chars for each row in a loop#
company = row[0]
for specialchars in char_cfg:
company = company.replace(specialchars, '')
cur.execute('Insert into transforms (Transresult1) values (\'' + company + '\')')
con.commit()
You forgot the cur.fetchall():
def transremovechars():
cur.execute('drop table transforms')
char_cfg = config.get('Transform_Variables', 'Chars_to_be_removed') #Reads all the special chars to be removed from specialchars.txt#
cur.execute('select * from originallist')
for row in cur.fetchall(): #Applies transformation to remove chars for each row in a loop#
company = row[0]
for specialchars in char_cfg:
company = company.replace(specialchars, '')
cur.execute('Insert into transforms (Transresult1) values (\'' + company + '\')')
con.commit()
You seem to drop your table transforms before working with it. Are you sure you want that? Or maybe have you forgotten to show the code which creates it again?
Your select * might e overkill if you only use the 1st column. Maybe you want to name that field in the SELECT.
Besides, you should replace your INSERT line with
cur.execute('Insert into transforms (Transresult1) values (?)', company)
Iterating over the cursor should be fine, however. Maybe you could insert some print statements into your for loop...
Comments to the effect that you should cur.fetchall() and iterate over that will work and be OK. The real fault in your code is that once you use cur to insert, it is a "new thing" and the original generator is reset (cur has the next()) method.
You can use cur without doing fetchall as you wanted, just create a second cursor ins_cur = con.curson() and use both. Many more advanced effects can be accomplished by iterating or using multiple cursors open on one connection.
And yes please use the correct variable binding for your dbapi module.

Categories

Resources