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>
Answer from Himanshu on Stack OverflowYou 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>
Sqlite3 is the version commonly used with Python. If you are running Windows, you need to download sqlite download from official page. If you are using Ubuntu or Debian based system then it comes pre-installed.
Now coming to python, sqlite3 is the package name, it comes included with python, if you don't find it, then install it with the command apt-get install python-sqlite on Ubuntu system.
Considering you are using Ubuntu system, simply type sqlite3 test.db to create database name test.db.
As for your program:
import sqlite3
conn = sqlite3.connect("test.db") # connect to test.db
cursor = conn.cursor() # get a cursor to the sqlite database
# cursor is the object here, you can use any name
# create a table
cursor.execute("""CREATE TABLE albums
(title text, artist text, release_date text,
publisher text, media_type text)""")
# cursor.execute is used to execute any command to sqlite
Few more function I would like to introduce is data = cursor.fetchone() to fetch one row, data = cursor.fetchall() to fetch many rows at once and store in tuple data.
In Python:
import sqlite3
con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
Watch out for my other answer. There is a much faster way using pandas.
You can fetch the list of tables and schemata by querying the SQLITE_MASTER table:
sqlite> .tab
job snmptarget t1 t2 t3
sqlite> select name from sqlite_master where type = 'table';
job
t1
t2
snmptarget
t3
sqlite> .schema job
CREATE TABLE job (
id INTEGER PRIMARY KEY,
data VARCHAR
);
sqlite> select sql from sqlite_master where type = 'table' and name = 'job';
CREATE TABLE job (
id INTEGER PRIMARY KEY,
data VARCHAR
)