Mc-
Mc-

Reputation: 4056

Python, Sqlite not saving results on the file

I have this code in Python:

conn = sqlite3.connect("people.db")
cursor = conn.cursor()

sql = 'create table if not exists people (id integer, name VARCHAR(255))'
cursor.execute(sql)
conn.commit()

sql = 'insert into people VALUES (3, "test")'
cursor.execute(sql)
conn.commit()   

sql = 'insert into people VALUES (5, "test")'
cursor.execute(sql)
conn.commit()  

print 'Printing all inserted'
cursor.execute("select * from people")
for row in cursor.fetchall():
    print row

cursor.close()
conn.close()

But seems is never saving to the database, there is always the same elements on the db as if it was not saving anything.

On the other side If I try to access the db file via sqlite it I got this error:

Unable to open database "people.db": file is encrypted or is not a database

I found on some other answers to use conn.commit instead of conn.commit() but is not changing the results.

Any idea?

Upvotes: 9

Views: 15020

Answers (4)

Dumisani Kunene
Dumisani Kunene

Reputation: 729

You should commit after making changes i.e:

myDatabase.commit()

Upvotes: 4

user3252247
user3252247

Reputation: 281

BINGO ! people! I Had the same problem. One of thr reasons where very simple. I`am using debian linux, error was

Unable to open database "people.db": file is encrypted or is not a database

database file was in the same dir than my python script connect line was
conn = sqlite3.connect('./testcases.db')

I changed this

conn = sqlite3.connect('testcases.db')

! No dot and slash. Error Fixed. All works

If someone think it is usefull, you`re welcome

Upvotes: 6

khz
khz

Reputation: 1

can you open the db with a tool like sqlite administrator ? this would proove thedb-format is ok. if i search for that error the solutions point to version issues between sqlite and the db-driver used. maybe you can chrck your versions or AKX could post the working combination.

regards,khz

Upvotes: 0

AKX
AKX

Reputation: 168863

This seems to work alright for me ("In database" increases on each run):

import random, sqlite3

conn = sqlite3.connect("people.db")
cursor = conn.cursor()

sql = 'create table if not exists people (id integer, name VARCHAR(255))'
cursor.execute(sql)

for x in xrange(5):
    cursor.execute('insert into people VALUES (?, "test")', (random.randint(1, 10000),))
conn.commit()

cursor.execute("select count(*) from people")
print "In database:", cursor.fetchone()[0]

Upvotes: 4

Related Questions