this is my python code to get all tickets from a sqlite database, where the "IR" number is the same. When I run it and search a value, sqlite prints only one row, for the value "IR". But there are two rows in my database. This is my Database:
Database content
def seek(IR):
conn = sqlite3.connect("Test.db")
cur = conn.cursor()
sql = "SELECT IR FROM Tickets WHERE IR = ?"
cur.execute(sql, (IR))
fetch = cur.fetchall()
print("Printing IR ", IR)
print("Total rows are: ", len(fetch))
for row in fetch:
print("IR: ", row[0])
print("Stellplatz: ", row[2])
conn.close()
I solve the issue on my own. I forgot the "*" in the SQL Statment.
Related
I am trying to get the fields of each row in stored procedure in a Postgres DB. I keep getting "tuple index out of range" I am basically copying and pasting the code from a tutorial website and still getting the same error.
When I do only row[0] it print out the entire query.
ConfRoom = ("ConfRoom1",612,1589540397,1589540425,/var/lib/freeswitch/recordings/10.91.50.217/archive/2020/May/15/7b4def4e-0494-439f-8540-1f339e3ec375,1a4652e7-61fc-4fb8-b564-19adec09ec0e)
tuple index out of range
#!/usr/bin/python3
import psycopg2
from config import config
def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# execute a statement
postgreSQL_select_Query = 'SELECT "public"."fn_get_recordings"()'
cur.execute(postgreSQL_select_Query)
conf_query = cur.fetchall()
print(conf_query)
for row in conf_query:
print("ConfRoom = ", row[0], )
print("ConfDescription = ", row[1])
print("StartEpoch = ", row[2])
print("EndEpoch = ", row[3])
print("Location = ", row[4])
print("MeetingID = ", row[5], "\n")
Thanks
select * from fn_get_recordings() worked.
I am trying to fetch records after a regular interval from a database table which growing with records. I am using Python and its pyodbc package to carry out the fetching of records. While fetching, how can I point the cursor to the next row of the row which was read/fetched last so that with every fetch I can only get the new set of records inserted.
To explain more,
my table has 100 records and they are fetched.
after an interval the table has 200 records and I want to fetch rows from 101 to 200. And so on.
Is there a way with pyodbc cursor?
Or any other suggestion would be very helpful.
Below is the code I am trying:
#!/usr/bin/python
import pyodbc
import csv
import time
conn_str = (
"DRIVER={PostgreSQL Unicode};"
"DATABASE=postgres;"
"UID=userid;"
"PWD=database;"
"SERVER=localhost;"
"PORT=5432;"
)
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
def fetch_table(**kwargs):
qry = kwargs['qrystr']
try:
#cursor = conn.cursor()
cursor.execute(qry)
all_rows = cursor.fetchall()
rowcnt = cursor.rowcount
rownum = cursor.description
#return (rowcnt, rownum)
return all_rows
except pyodbc.ProgrammingError as e:
print ("Exception occured as :", type(e) , e)
def poll_db():
for i in [1, 2]:
stmt = "select * from my_database_table"
rows = fetch_table(qrystr = stmt)
print("***** For i = " , i , "******")
for r in rows:
print("ROW-> ", r)
time.sleep(10)
poll_db()
conn.close()
I don't think you can use pyodbc, or any other odbc package, to find "new" rows. But if there is a 'timestamp' column in your database, or if you can add such a column (some databases allow for it to be automatically populated as the time of insertion so you don't have to change the insert queries) then you can change your query to select only the rows whose timestamp is greater than the previous timestamp. And you can keep changing the prev_timestamp variable on each iteration.
def poll_db():
prev_timestamp = ""
for i in [1, 2]:
if prev_timestamp == "":
stmt = "select * from my_database_table"
else:
# convert your timestamp str to match the database's format
stmt = "select * from my_database_table where timestamp > " + str(prev_timestamp)
rows = fetch_table(qrystr = stmt)
prev_timestamp = datetime.datetime.now()
print("***** For i = " , i , "******")
for r in rows:
print("ROW-> ", r)
time.sleep(10)
I'm a bit curious what is the pythonic/best way to solve my issue.
A short code example:
import pymssql
conn = pymssql.connect("SERVER", 'sa', 'PASSWORD', 'DATABASE', charset='utf8')
cursor = conn.cursor()
sql = "SELECT 'foo\bar' as bs_field"
cursor.execute(sql)
row = cursor.fetchone()
print row[0]
# missing \, returns u'foobar'
sql = "select FIELD_CONTAINING_BACKSLASH from TABLE"
cursor.execute(sql)
row = cursor.fetchone()
print row[0]
# all OK here
sql = "SELECT 'foo\\bar' as bs_field"
cursor.execute(sql)
row = cursor.fetchone()
print row[0]
# this is OK too
I want to know why the \ is missing in the first example - is there a better solution as quoting every single sql?
I am an idiot!
Has nothing to do with mssql, it's just python strings.
r'bla\bla'
'bla\\bla'
Reference: https://docs.python.org/2.0/ref/strings.html
Hell guys just jumped in to python and i'm having a hard time figuring this out
I have 2 queries . . query1 and query2 now how can i tell
row = cursor.fetchone() that i am refering to query1 and not query2
cursor = conn.cursor()
query1 = cursor.execute("select * FROM spam")
query2 = cursor.execute("select * FROM eggs")
row = cursor.fetchone ()
thanks guys
Once you perform the second query, the results from the first are gone. (The return value of execute isn't useful.) The correct way to work with two queries simultaneously is to have two cursors:
cursor1 = conn.cursor()
cursor2 = conn.cursor()
cursor1.execute("select * FROM spam")
cursor2.execute("select * FROM eggs")
cursor1.fetchone() #first result from query 1
cursor2.fetchone() #first result from query 2
It doesn't. The return value from cursor.execute is meaningless. Per PEP 249:
.execute(operation[,parameters])
Prepare and execute a database operation (query or
command)...
[...]
Return values are not defined.
You can't do it the way you're trying to. Do something like this instead:
cursor = conn.cursor()
cursor.execute("select * FROM spam")
results1 = cursor.fetchall()
cursor.execute("select * FROM eggs")
if results1 is not None and len(results1) > 0:
print "First row from query1: ", results1[0]
row = cursor.fetchone()
if row is not None:
print "First row from query2: ", row
Using python and MySQLdb, how can I check if there are any records in a mysql table (innodb)?
Just select a single row. If you get nothing back, it's empty! (Example from the MySQLdb site)
import MySQLdb
db = MySQLdb.connect(passwd="moonpie", db="thangs")
results = db.query("""SELECT * from mytable limit 1""")
if not results:
print "This table is empty!"
Something like
import MySQLdb
db = MySQLdb.connect("host", "user", "password", "dbname")
cursor = db.cursor()
sql = """SELECT count(*) as tot FROM simpletable"""
cursor.execute(sql)
data = cursor.fetchone()
db.close()
print data
will print the number or records in the simpletable table.
You can then test if to see if it is bigger than zero.