This is a common problem it seems on here but in my case I cant find an answer. Why is it saying inconsistent use of tabs and indentation here
def exectute_SQL(): #This function executes SQL to pull counts from a table where it wasnt possible to get an excel
con = pypyodbc.connect(conn_str)
cur = con.cursor()
sql = "SELECT * FROM Elig_Own.DST_Report_Validation_Test" #WHERE ysn_active = '1'"
cur.execute(sql)
rows = cur.fetchall()
for row in rows:
strFnd = 0
strReportName = row[1]
strSrcName = row[2]
strDestName = row[3]
strFileName = row[4]
try:
for report in strReportName:
if report == 'STR_DB Load to SQL':
cur.execute("$result = SELECT TOP 1 COUNT(*) FROM Elig_Own.STR_DB GROUP BY LAST_UPDATED ORDER BY LAST_UPDATED DESC;")
cur.execute("INSERT INTO Elig_Own.DST_Report_Status_Test(TDate, Report, Records, Status) VALUES(CAST(GetDate() AS Date), 'STR_DB Load to SQL', ?, 'Passed')",(result))
con.commit()
except:
print("Couldnt execute script")
And This is the error message
C:\Users\cn192406\Documents\Programs>python File_Check_Dart_Functions.py
File "File_Check_Dart_Functions.py", line 73
cur.execute("$result = SELECT TOP 1 COUNT(*) FROM Elig_Own.STR_DB GROUP BY LAST_UPDATED ORDER BY LAST_UPDATED DESC;")
TabError: inconsistent use of tabs and spaces in indentation
Try this:
def exectute_SQL(): # This function executes SQL to pull counts from a table where it wasnt possible to get an excel
con = pypyodbc.connect(conn_str)
cur = con.cursor()
sql = "SELECT * FROM Elig_Own.DST_Report_Validation_Test" # WHERE ysn_active = '1'"
cur.execute(sql)
rows = cur.fetchall()
for row in rows:
strFnd = 0
strReportName = row[1]
strSrcName = row[2]
strDestName = row[3]
strFileName = row[4]
try:
for report in strReportName:
if report == "STR_DB Load to SQL":
cur.execute(
"$result = SELECT TOP 1 COUNT(*) FROM Elig_Own.STR_DB GROUP BY LAST_UPDATED ORDER BY LAST_UPDATED DESC;"
)
cur.execute(
"INSERT INTO Elig_Own.DST_Report_Status_Test(TDate, Report, Records, Status) VALUES(CAST(GetDate() AS Date), 'STR_DB Load to SQL', ?, 'Passed')",
(result),
)
con.commit()
except Exception as e:
pass
Related
I am trying to run an execute statement with python in sql to return all the ids that match up with one value, in this case x. There are multiple items that should match the variable(x) that I am trying to pass through but when I run this line I only get one item in the list and the rest get left behind. When I execute the line in the sqlite browser it give me a table with all the matching data I want but for some reason this doesn't pass it all into the list.
cur.execute('SELECT movie_id FROM MG WHERE genre_id = ?', (x, ))
for x in cur:
midg.append(y[0])
Here is my entire code so far:
gnames = list()
cur.execute('SELECT genre_name FROM Genre')
for row in cur:
gnames.append(row[0])
print(gnames)
gid = list()
midg = list()
grating = list()
grate = dict()
for namew in gnames:
gid.clear()
grating.clear()
midg.clear()
cur.execute('SELECT genre_id FROM Genre WHERE genre_name = ?', (namew, ))
x = cur.fetchone()[0]
cur.execute('SELECT movie_id FROM MG WHERE genre_id = ?', (x, ))
for x in cur:
midg.append(y[0])
for z in midg:
cur.execute('SELECT movie_rating FROM Movie WHERE movie_id = ?', (z, ))
for row in cur:
grating.append(row[0])
gaverage = sum(grating)/len(grating)
grate[namew] = gaverage
try it.
#Install package
#pip install pyodbc
import pyodbc
server = 'server'
database = 'database'
username = 'username'
password = 'password'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("SELECT * from INFORMATION_SCHEMA.TABLES")
row = cursor.fetchone()
while row:
#TABLE_CATALOG
print(row[0])
print()
#TABLE_SCHEMA
print(row[1])
print()
#TABLE_NAME
print(row[2])
print()
# TABLE_TYPE
print(row[3])
print()
print('all columns')
print(str(row[0]), "-",str(row[1]), "-",str(row[2]), "-",str(row[3]))
row = cursor.fetchone()
I'm trying to "SELECT" a value from Db and add this value to another variable, but when I execute this I get this error "TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' "
id = input("Digite o id do cartão: ")
cash = int(input("Digite o o valor a ser creditado: "))
dia = 3
sql = 'SELECT saldo FROM carteira where idcartao = ?'
def selectbanco():
c.execute("SELECT saldo FROM carteira WHERE idcartao=?", (id,))
row = c.fetchone()
print(row)
row = c.fetchone()
soma = (row) + (cash)
c.execute("UPDATE carteira SET saldo=? WHERE idcartao=?", (soma, id))
connection.commit()
selectbanco()
THIS IS MY COMPLETE CODE
import sqlite3
connection = sqlite3.connect('clientes.db')
c = connection.cursor()
#criação de tabela
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS carteira (idcartao REAL, saldo REAL, data text)')
create_table()
#variaveis
id = input("Digite o id do cartão: ")
cash = int(input("Digite o o valor a ser creditado: "))
dia = 3
sql = 'SELECT saldo FROM carteira where idcartao = ?'
#SELECT E RETORNAR VALOR
def selectbanco():
c.execute("SELECT saldo FROM carteira WHERE idcartao=?", (id,))
row = c.fetchone()
print(row)
row = c.fetchone()
##soma = (row + cash)
##print(soma)
c.execute("UPDATE carteira SET saldo=? WHERE idcartao=?", (cash, id))
connection.commit()
selectbanco()
#leitura do banco
def read_data(wordUsed):
for row in c.execute(sql, (wordUsed,)):
print (row)
read_data(id)
connection.close()
You've got two issues here.
The first is that you exhaust your generator by calling row = c.fetchone() twice, without re-executing the query. You can only iterate through your cursor once for each query result; after that, you will need to re-run the query to "refresh" the data and be able to iterate again.
Second, fetchone() will actually return None if you get no matches. This is in contrast to fetchall() that will instead return an empty list ([]) in the case of no matches.
This quick example should illustrate this behaviour:
import sqlite3
# Create a fake database
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS some_table(
something TEXT
)""")
c.execute(""" INSERT INTO some_table VALUES('hello') """)
c.execute("SELECT * FROM some_table")
# We get a match and this will print '(hello,)'
data = c.fetchone()
print(data)
data = c.fetchone()
# If we don't execute the query again but try to use the exhausted generator
# then we'll also get None
print(data)
c.execute("SELECT * FROM some_table WHERE something = 'bye'")
# This will print 'None' because fetchone() didn't get a result
data = c.fetchone()
print(data)
c.execute("SELECT * FROM some_table WHERE something = 'bye'")
# This will print an empty list because fetchall() didn't get a result
data = c.fetchall()
print(data)
c.close()
conn.close()
Even though None and [] are different, they are still falsey so, in the context of your question, you can still convert either response to an integer:
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("""create table if not exists some_table(
something TEXT
)""")
c.execute(""" INSERT INTO some_table VALUES('hello') """)
# Get back None or an integer
c.execute(""" SELECT * FROM some_table WHERE something = ?""", ('bye', ))
data = c.fetchone() or 1 # This is where you return an integer instead of None
print(data)
c.close()
conn.close()
I've picked an integer value of 1, maybe you want 0, I'm not sure. The thing to note, though, is that there's two avenues for you to get None or falsey data here, and you're treating them both the same, which isn't great for clarity of code.
You are fetching row twice. You need to remove the second fetch to receive the row.
def selectbanco():
c.execute("SELECT saldo FROM carteira WHERE idcartao=?", (id,))
row = c.fetchone()
print(row)
soma = (row) + (cash)
c.execute("UPDATE carteira SET saldo=? WHERE idcartao=?", (soma, id))
connection.commit()
selectbanco()
The variable gets overwritten because you do not specify a command to execute before fetching (the second time), hence the NoneType.
I get the error not all arguments converted during string formatting, when I execute the below-given code:
pro_title = "FSBT"
print "pro_title: " + pro_title
pro_id_query = "SELECT ID FROM projs WHERE pro_title=%s"
cursor.execute(pro_id_query, pro_title)
db.commit()
row = cursor.fetchone()
pro_id = None
if row is not None:
pro_id = str(row[0])
print "pro_id: " + pro_id
I also tried format:
pro_id_query = "SELECT ID FROM projs WHERE title={}"
cursor.execute(pro_id_query.format(pro_title))
It only works when I use ' around {}:
pro_id_query = "SELECT ID FROM projs WHERE title='{}'"
cursor.execute(pro_id_query.format(pro_title))
I do not understand why INSERT queries work well with %s, while SELECT queries do not:
insert_query = "INSERT INTO projs (title, description) VALUES (%s, %s) ON DUPLICATE KEY UPDATE `title`=%s"
cursor.execute(insert_query, (pro_title, pro_description, pro_title))
pro_title = "FSBI"
pro_id_query = "SELECT * FROM %s"%(pro_title)
cursor = con.cursor()
cursor.execute(q)
result_list = result.fetchall()
result_list[0][0]
con.commit()
con.close()
pro_id_query = cursor.fetchone() while row != False:
print ("The ID is : ", row[0])
*edit
id = input("Id : ")
name = input("Name : ")
cursor = con.cursor()
cursor.execute(""" INSERT INTO names (id, name) VALUES("%s", "%s")"""
%(id, name))
I'm not sure why I get this error when I test this function. Can anyone please help me fix this?
time_file.readlines()
builtins.ValueError: I/O operation on closed file.
I want to create a table for the time and insert all the values listed below, like idx, date, start, end, duration into the table.
def create_time_table(db, time_file):
'''Time Table should be ID,Date,Start,End,Duration
'''
con = sqlite3.connect(db)
cur = con. cursor()
cur.execute('''DROP TABLE IF EXISTS Time''')
# create the table
cur.execute('''CREATE TABLE TIME(idTEXT, DateTEXT, StartTEXT, EndTEXT,
DurationTEXT)''')
# insert the rows
time_file.readlines()
for line in time_file:
data = line.split(',')
idx = data[0]
date = data[1]
start = data[2]
end = data[3]
duration = data[4]
cur.execute('''INSERT INTO TIME VALUES(?, ?, ?, ?, ?)''',(idx, date, start, end, duration))
if __name__ == '__main__':
file2 = open('time.csv', 'r')
create_time_table("exams.db", file2)
file2.close()
#bigd since we are in the same class lol... here is the solution.. Your mistake is how you are reading the file, it should be time_file.readline(), if you do time_file.readlines(), using sqliteonline, the table would not appear.
def create_time_table(db, time_file):
'''Time Table should be ID,Date,Start,End,Duration
'''
con = sqlite3.connect(db)
cur = con. cursor()
cur.execute('''DROP TABLE IF EXISTS Time''')
# create the table
cur.execute('''CREATE TABLE Time(ID TEXT, Date TEXT, Start TEXT, End TEXT,
DurationTEXT)''')
# insert the rows
clock_file = open(time_file, 'r')
clock_file.readline()
for line in clock_file:
data = line.strip().split(',')
idx = data[0]
date = data[1]
start = data[2]
end = data[3]
duration = data[4]
cur.execute('''INSERT INTO TIME VALUES(?, ?, ?, ?, ?)''',(idx, date, start, end, duration))
# commit and close the cursor and connection
con.commit()
cur.close()
con.close()
## Under if __name__ == '__main__': ##
create_time_table('exams.db', 'time.csv')
It can't figure out the fetchone()[0] part and why when I change [0] to [1], [2] etc. my table is not looking so good (every emails counter is 1 and so every email is duplicated if there is more than one of the same email in the file).
import sqlite3
con = sqlite3.connect('db1.sqlite')
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS TimesSend')
cur.execute('CREATE TABLE TimesSend(email TEXT,times INTEGER)')
file = open('file.txt','r')
for row in file:
if not row.startswith('From: '):
continue
parts = row.split()
mail = parts[1]
print(mail)
cur.execute('SELECT timesFROM TimesSend WHERE email= ?', (mail,))
try:
times = cur.fetchone()[0]
cur.execute('UPDATE TimesSend SET times=times+1 WHERE email=?', (mail,))
except:
cur.execute('INSERT INTO TimesSend (email,puta) VALUES(?,1)', (mail,))
con.commit()
Your code has some issue, please try below:
import sqlite3
con = sqlite3.connect('db1.sqlite')
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS TimesSend')
cur.execute('CREATE TABLE TimesSend(email TEXT,times INTEGER)')
file = open('file.txt','r')
for row in file:
if not row.startswith('From: '):
continue
parts = row.split()
mail = parts[1]
print(mail)
cur.execute('SELECT times FROM TimesSend WHERE email= ?', (mail,))
try:
# fetchone() will be a tuple (1,),
# then you should use index 0 to select times 1
times = cur.fetchone()[0]
print(times)
# if duplicate, times+1
cur.execute('UPDATE TimesSend SET times=? WHERE email=?', (times+1, mail))
except:
cur.execute('INSERT INTO TimesSend (email,times) VALUES(?,1)', (mail,))
con.commit()
print(cur.execute('SELECT * FROM TimesSend').fetchall())
con.close()
Print output will be:
testa#gmail.com
testa#gmail.com
1
testc#gmail.com
testd#gmail.com
testb#gmail.com
[(u'testa#gmail.com', 2), (u'testc#gmail.com', 1), (u'testd#gmail.com', 1), (u'testb#gmail.com', 1)]