Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

sqlite - How to work with sqlite3 and Python

I was looking for any database solution with Python. And found the tutorial Python: A Simple Step-by-Step SQLite Tutorial. There I found a code example which shows how to create a database and INSERT some data:

import sqlite3

conn = sqlite3.connect("mydatabase.db") # or use :memory: to put it in RAM

cursor = conn.cursor()

# create a table
cursor.execute("""CREATE TABLE albums
                  (title text, artist text, release_date text, 
                   publisher text, media_type text) 
               """)

I am totally new to sqlite3.

  • If I want to use sqlite3 do I need to install any particular Python modules?
  • In the above code I can see one database named mydatabase.db. How do I create that database?

If anyone help me to get these confusions cleared from my head, I can give these new module a good start.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need (to install) any additional Python modules to use sqlite3.

If the database doesn't exist, it will be automatically created usually in the same directory as the script.

On running your script, I get this :-

$ ls *.db
ls: *.db: No such file or directory

$ python test.py

$ ls *.db
mydatabase.db

$ sqlite3 mydatabase.db 
SQLite version 3.7.7 2011-06-25 16:35:41
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from sqlite_master;
table|albums|albums|2|CREATE TABLE albums
             (title text, artist text, release_date text, 
              publisher text, media_type text)
sqlite> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...