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')
Related
This is my first project with SQLite.
The code runs perfect I checked and the lines look perfect.
I supposed that due to lack of knowledge of SQLite I'm making a mistake.
Problem: The code runs perfect no problem. But when I finish it doesn't print the values or even save the values in the .db file.
Full Code:
import sqlite3
import datetime
import time
conn = sqlite3.connect('covid.db')
c = conn.cursor()
def create_table():
c.execute('''CREATE TABLE IF NOT EXISTS
covidTrack(
name TEXT,
email TEXT,
ph_number INTEGER,
datestamp TEXT,
keyword TEXT)''')
i_name = input('Please insert FULL NAME : \n ...')
i_email = input('Please insert EMAIL : \n ...')
i_number = input('Please insert PHONE NUMBER : \n ...')
print('Your data has been saved for acelerated contact, thank you.')
time.sleep(3)
def data_entry():
c.execute('INSERT INTO covidTrack VALUES(?,?,?)',
(i_name, i_email, i_number))
conn.commit()
def dynamic_data_entry():
keyword = nameofvenue
date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%M-%D %h:%m:%s'))
c.execute('INSERT INTO covidTrack VALUES(date, keyword)')
conn.commit()
def read_from_db():
c.execute('''SELECT * FROM covidTrack
WHERE datestamp
BETWEEN "2021-02-06 14:50:00" AND "2021-02-06 15:00:00"''')
conn.commit()
for row in c.fetchall():
print(row)
create_table()
data_entry()
dynamic_data_entry()
read_from_db()
c.close()
conn.close()
I suppose if something wrong with the way I use conn.commit().
import sqlite3
import datetime
import time
conn = sqlite3.connect('covid.db')
c = conn.cursor()
def create_table():
c.execute('''CREATE TABLE IF NOT EXISTS
covidTrack(
name TEXT,
email TEXT,
ph_number INTEGER,
datestamp TEXT,
keyword TEXT)''')
i_name = input('Please insert FULL NAME : \n ...')
i_email = input('Please insert EMAIL : \n ...')
i_number = input('Please insert PHONE NUMBER : \n ...')
print('Your data has been saved for acelerated contact, thank you.')
time.sleep(3)
def data_entry():
date, keyword = dynamic_data_entry()
c.execute('INSERT INTO covidTrack VALUES(?, ?, ?, ?, ?)', (i_name, i_email, i_number, date, keyword))
conn.commit()
def dynamic_data_entry():
keyword = 'nameofvenue'
date = str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%M-%D %h:%m:%s'))
return date, keyword
def read_from_db():
c.execute('''SELECT * FROM covidTrack''')
conn.commit()
create_table()
data_entry()
read_from_db()
for row in c.fetchall():
print(row)
c.close()
conn.close()
change the code below (make the commit call part of the function that insert the data). Do it in dynamic_data_entry as well
def dynamic_data_entry():
keyword = nameofvenue
date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%M-%D %h:%m:%s'))
c.execute('INSERT INTO covidTrack VALUES(date, keyword)')
conn.commit()
to
def dynamic_data_entry():
keyword = nameofvenue
date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%M-%D %h:%m:%s'))
c.execute('INSERT INTO covidTrack VALUES(date, keyword)')
conn.commit()
You do not actually commiting your executes. Move conn.commit after actual executes.
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
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.
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)]
I'm attempting to get a python script to insert data into a database without having it drop the table first.. I'm sure this isn't hard to do but I can't seem to get the code right..
Here is the full python script..
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import hashlib
import time
import MySQLdb
#Dont forget to fill in PASSWORD and URL TO saveTemp (twice) in this file
sensorids = ["28-000004944b63", "28-000004c01b2c"]
avgtemperatures = []
for sensor in range(len(sensorids)):
temperatures = []
for polltime in range(0,3):
text = '';
while text.split("\n")[0].find("YES") == -1:
# Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before.
tfile = open("/sys/bus/w1/devices/"+ sensorids[sensor] +"/w1_slave")
# Read all of the text in the file.
text = tfile.read()
# Close the file now that the text has been read.
tfile.close()
time.sleep(1)
# Split the text with new lines (\n) and select the second line.
secondline = text.split("\n")[1]
# Split the line into words, referring to the spaces, and select the 10th word (counting from 0).
temperaturedata = secondline.split(" ")[9]
# The first two characters are "t=", so get rid of those and convert the temperature from a string to a number.
temperature = float(temperaturedata[2:])
# Put the decimal point in the right place and display it.
temperatures.append(temperature / 1000 * 9.0 / 5.0 + 32.0)
avgtemperatures.append(sum(temperatures) / float(len(temperatures)))
print avgtemperatures[0]
print avgtemperatures[1]
#connect to db
db = MySQLdb.connect("localhost","user","password","temps" )
#setup cursor
cursor = db.cursor()
#create temps table
cursor.execute("DROP TABLE IF EXISTS temps")
sql = """CREATE TABLE temps (
temp1 FLOAT,
temp2 FLOAT )"""
cursor.execute(sql)
#insert to table
try:
cursor.execute("""INSERT INTO temps VALUES (%s,%s)""",(avgtemperatures[0],avgtemperatures[1]))
db.commit()
except:
db.rollback()
#show table
cursor.execute("""SELECT * FROM temps;""")
print cursor.fetchall()
((188L, 90L),)
db.close()
This is the part I need assistance with..
If I have it drop the table it works fine but I don't want it to drop the table, just insert the new data into the same table.
#connect to db
db = MySQLdb.connect("localhost","user","pasword1","temps" )
#setup cursor
cursor = db.cursor()
#create temps table
cursor.execute("DROP TABLE IF EXISTS temps")
sql = """CREATE TABLE temps (
temp1 FLOAT,
temp2 FLOAT )"""
cursor.execute(sql)
#insert to table
try:
cursor.execute("""INSERT INTO temps VALUES (%s,%s)""",(avgtemperatures[0],avgtemperatures[1]))
db.commit()
except:
db.rollback()
#show table
cursor.execute("""SELECT * FROM temps;""")
print cursor.fetchall()
((188L, 90L),)
db.close()
You shouldn`t have to drop a table each time you want to enter data. In fact, it defeats the whole purpose of the database since you will remove all the previous data each time you run your script.
You should ask to create the table but only if it does not exists. Use the following.
sql = """CREATE TABLE IF NOT EXISTS temps (
temp1 FLOAT,
temp2 FLOAT )"""
cursor.execute(sql)
I've had this problem with updating. Try adding COMMIT to the end of your sql. I use psycopg2 to connect to a postgresql database. Here is an example.
def simple_insert():
sql = '''INSERT INTO films VALUES ('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes'); COMMIT;'''
try:
conn = psycopg2.connect(database)
cur = conn.cursor()
cur.execute(sql)
except:
raise
I think your problem is your not saving the transaction and the COMMIT command should fix it.