The major problem I have is that the "SELECT COUNT(*)" statement is always wrong (the total number of rows is always "2"), and so I can't insert a new row to the database.
I tried using "con.commit()", from what I read in other questions, but it still doesn't work. And if I change the "filename", it would just replace the previous written row. I specified columns to be unique and added a primary key. Still no new record.
from time import ctime
import sqlite3
def Main():
try:
con = sqlite3.connect('textdb.db')
con.commit()
cur = con.cursor()
cur.executescript("""DROP TABLE IF EXISTS file_info;
CREATE TABLE file_info(file_id INTEGER NOT NULL PRIMARY KEY UNIQUE, file_name TEXT NOT NULL UNIQUE, file_content TEXT, date_created TEXT NOT NULL, date_updated TEXT NOT NULL);
INSERT INTO file_info VALUES(1, 'first', 'This is just an example.', 'Mon Dec 29 15:35:36 2014', 'Mon Dec 29 15:35:36 2014');
INSERT INTO file_info VALUES(2, 'another', 'Another example.', 'Mon Dec 29 15:59:49 2014', 'Mon Dec 29 16:00:23 2014');""")
con.commit()
myrows = cur.execute("SELECT * FROM file_info")
for row in myrows:
cur.execute("SELECT COUNT(*) FROM file_info")
count_row = cur.fetchone()
cntdata = count_row[0]
print (cntdata)
filename = 'example'
t = 'Yes, it works!'
curtime = str(ctime())
inc = (cntdata + 1)
print(inc)
cur.execute("INSERT OR IGNORE INTO file_info VALUES(?, ?, ?, ?, ?)", (inc, filename, t, curtime, curtime,))
con.commit()
except sqlite3.Error:
if con:
con.rollback()
finally:
if con:
con.close()
if name == 'main': Main()
Aucun commentaire:
Enregistrer un commentaire