0
import sqlite3
db=sqlite3.connect('new.db')
cursor=db.cursor()
cursor.execute('''CREATE TABLE hello(id INTEGER PRIMARY KEY,
Message_type, time_sent, time_received, response)''')

The above program when executed from the python shell will execute and create a database by the said name but when i run the same program from a .py file,it won't create any table or database

4
  • How do you know that it didn't create the table? Does it produce an error message? Commented Jul 21, 2016 at 14:26
  • Because i manually check it by a database browser.-dbbrowser for sqlite Commented Jul 21, 2016 at 14:28
  • What happens if you add db.commit() and db.close() in the script? Commented Jul 21, 2016 at 15:56
  • Same results even if you add db.commit() & close() Commented Jul 22, 2016 at 4:47

2 Answers 2

1
import sqlite3
from os.path import expanduser
db_dir = expanduser("~")
db=sqlite3.connect(db_dir+'/new.db')
cursor=db.cursor()
cursor.execute('''CREATE TABLE hello(id INTEGER PRIMARY KEY,
Message_type, time_sent, time_received, response)''')

Now look in your home directory for new.db

Sign up to request clarification or add additional context in comments.

3 Comments

The code that your provided me with created the database but its read only ,i cannot make any changes to it. Is there a way to make it read/write by any user?
That is probably because it is in your $HOME directory. Make db_dir equal to somewhere to which everyone else has access. /home/public or something.
I fixed it by some basic linux command that changes ownership of the created database.
0

I suppose that the .py file did create the database file, but you aren't looking for the database file at the correct location. Add this to the end of your program:

print(os.path.join(os.getcwd(), 'new.db'))

Whatever it prints, look there for your database file.

3 Comments

Does the python shell and .py file save .db files in different directories?
That depends upon how they are each invoked. Since you don't specify how you invoke either, this seems like a possibility.
I tried your suggestion. However the data base is not in the location returned by the os.path command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.