Here is my code:
dbContent = cursor.execute("SELECT COUNT(*) FROM parse")
if dbContent is None:
# This should run the nested code if it worked.
Instead it runs the else statement which is not what should be happening.
I am not a python expert but I think your code is just not correct. Please try this instead:
cursor.execute("SELECT COUNT(*) FROM parse")
result=cursor.fetchone()
numRows=result[0]
if numRows == 0:
# run your code
dbContent = cursor.execute("SELECT COUNT(*) FROM parse")
rows = dbContent.fetchall()
if not rows:
...
Lists have implicit booleanness which you can use.
Related
I am trying to understand how to capture the number of records deleted from a delete command in Python code using psycopg2. Typically after a delete command is issued in PostgreSql the number of rows deleted appears (i.e., DELETE 8, where 8 represents the number of rows deleted). I would like to record this count after each delete in order to report back to the caller the number of rows deleted without needing to make a separate SELECT count(*) before the DELETE command.
Consider this function:
def qexe(conn, query, fetch_type):
cursor = conn.cursor()
cursor.execute(query)
if fetch_type != None:
if fetch_type == 'fetchall':
query_result = cursor.fetchall()
return query_result
elif fetch_type == 'fetchone':
query_result = cursor.fetchone()
return query_result
else:
raise Exception(f"Invalid arg fetch_type: {fetch_type}")
cursor.close()
After running each of the following, I keep getting the error: psycopg2.ProgrammingError: no results to fetch:
qq = """DELETE FROM INV WHERE ITEM_ID = '{}';"""
item='123abc'
resp0 = qexe(conn, qq.format(item), 'fetchone')
resp1 = qexe(conn, qq.format(item), 'fetchall')
You could make use of RETURNING, so you will be able to get 'something' back which can be fetched from the cursor:
qq = """DELETE FROM INV WHERE ITEM_ID = '{}' RETURNING ITEM_ID"""
resp0 = qexe(conn, qq.format(item), 'fetchone')
I need to print some rows from an sqlite3's table using python3, but into the loop I get none value. following my code:
import sqlite3
db=sqlite3.connect('db.db')
cdb=db.cursor()
cdb.execute('create table if not exists table1 (field1,field2,field3)')
cdb.execute('insert into table1 values (?,?,?)',(1,2,3))
db.commit()
cdb.execute('insert into table1 values (?,?,?)',(4,5,6))
db.commit()
cdb.execute('insert into table1 values (?,?,?)',(1,7,8))
db.commit()
cdb.execute('select * from table1')
for i in range(len(cdb.fetchall())):
if cdb.fetchone()[0]==1:print(cdb.fetchone())
db.close()
my error message:
AttributeError: 'NoneType' object has no attribute 'replace'
Thanks
Your call to cdb.fetchall() consumes the iterator and is pointless, so remove it:
for row in cdb.execute('select * from table1'):
# do something with row
As described in the official documentation.
After you fetchall the cursor point to nothing, so if you fetch anything it returns None.
to see what happend after commit the data just try:
cdb.execute('select * from table1')
print(cdb.fetchall()) # Return the data
print(cdb.fetchone()) # Return : None
db.close()
to fix this you could execute the sql again before the fetchone witch will be slow
I recommend doing this:
cdb.execute('select * from table1')
data = cdb.fetchall()
for i in data:
if i[0] == 1: print(i)
db.close()
import pymssql
import decimal
CONN = pymssql.connect(server='1233123123', user='s123', password='sa1231231', database='DBforTEST')
CURSOR = CONN.cursor()
"""it is good code. here is no problem"""
CURSOR.execute("SELECT ttt from test where w=2")
ROW = CURSOR.fetchone()
tmp = list()
tmp.append(ROW)
if ROW is None:
print("table has nothing")
else:
while ROW:
ROW = CURSOR.fetchone()
tmp.append(ROW)
print(tmp)
"""it works!"""
CURSOR.execute("""
UPDATE test
SET
w = 16
where ttt = 1
""")
"it doesnt works"
I'm using python 3.5 with pymssql.
In my code, SELECT state works, so I can guarantee the connection is perfect.
But the UPDATE state doesn't work in Python.
The same code works in SSMS.
What is the problem?
I guess SELECT state is only for read, so DB can provide Data, but UPDATE is modifying DB, so DB blocks it.
How can I solve it?
CONN.commit()
if autocommit is not set then you have to commit yourself.
I'm trying to check whether a variable exists in an SQLite3 db. Unfortunately I can not seem to get it to work. The airports table contains 3 colums, with ICAO as the first column.
if c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO='EHAM')") is True:
print("Found!")
else:
print("Not found...")
The code runs without any errors, but the result is always the same (not found).
What is wrong with this code?
Try this instead:
c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO='EHAM')")
if c.fetchone():
print("Found!")
else:
print("Not found...")
Return value of cursor.execute is cursor (or to be more precise reference to itself) and is independent of query results. You can easily check that:
>>> r = c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO='EHAM')")
>>> r is True
False
>>> r is False
False
>>> r is None
False
>>> r is c
True
From the other hand if you call cursor.fetchone result tuple or None if there is no row that passes query conditions. So in your case if c.fetchone(): would mean one of the below:
if (1, ):
...
or
if None:
...
Let's prepare a database to test it.
import sqlite3
c = sqlite3.connect(":memory:")
c.execute("CREATE TABLE airports (ICAO STRING, col2 STRING, col3 STRING)")
c.execute("INSERT INTO airports (ICAO, col2, col3) VALUES (?, ?, ?)", ('EHAM', 'value2', 'value3'))
Since your SELECT 1 FROM airports WHERE ICAO = 'EHAM' already serves the purpose of checking existence, let's use it directly, without the redundant SELECT EXISTS()
if c.execute("SELECT 1 FROM airports WHERE ICAO = 'EHAM'").fetchone():
print("Found!")
else:
print("Not found...")
the result is
Found!
Let's check a non-existent case
if c.execute("SELECT 1 FROM airports WHERE ICAO = 'NO-SUCH'").fetchone():
print("Found!")
else:
print("Not found...")
the result is
Not found...
If you just want to fix your code, you can try
if c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO = 'EHAM')").fetchone() == (1,):
print("Found!")
else:
print("Not found...")
the result is
Found!
Thanks for the answer from zero323, although the code snippet is wrong, as fetchone() does not return True or False. It only returns 1 for True and 0 for False. (binary) The following code works without problems in Python3:
response = self.connection.execute("SELECT EXISTS(SELECT 1 FROM invoices WHERE id=?)", (self.id, ))
fetched = response.fetchone()[0]
if fetched == 1:
print("Exist")
else:
print("Does not exist")
I don't have the reputation to comment. However, the comments and answers claiming that the top answer is incorrect are erroneous. In Python, 1 and 0 are synonymous with True and False, respectively. In fact, the substitution of 1 for True and 0 for False are very Pythonic, i.e. highly condoned in Python.
In short, the top answer of if c.fetchone(): is correct.
Checking for equality with 1, if c.fetchone() == 1:, is unnecessary and against Python best practices.
Anyone know of a handy function to search through column_names in Vertica? From the documentation, it seems like \d only queries table_names. I'm looking for something like MySQL's information_schema.columns, but can't find any information about a similar table of meta-data.
Thanks!
In 5.1 if you have enough permissions you can do
SELECT * FROM v_catalog.columns;
to access columns's info, for some things you'll need to join with
v_catalog.tables
The answer may differ depending on the version of Vertica you are using.
In the latest version, 5.1, there is a COLUMNS system table. Just from looking at the online documentation here seems to be the most useful columns with their types:
TABLE_SCHEMA VARCHAR
TABLE_NAME VARCHAR
DATA_TYPE VARCHAR
That should give you what you need. If your version doesn't have the system table, let me know what version you're running and I'll see what we can do.
Wrap this python script in a shell function and you'll be able to see all tables that contain any two columns:
import argparse
parser = argparse.ArgumentParser(description='Find Vertica attributes in tables')
parser.add_argument('names', metavar='N', type=str, nargs='+', help='attribute names')
args = parser.parse_args()
def vert_attributes(*names):
first_name = names[0].lower()
first = "select root.table_name, root.column_name from v_catalog.columns root "
last = " where root.column_name like '%s' " % first_name
names = names[1:]
if len(names) >= 1:
return first + " ".join([" inner join (select table_name from v_catalog.columns where column_name like '%s') q%s on root.table_name = q%s.table_name " % (name.lower(), index, index) for index,name in enumerate(names)]) + last
else:
return first + last
print nz_attributes(*tuple(args.names))