No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python sqlite3 Create Tables

by Khaleel O.
August 6, 2021
in Python
Reading Time: 4 mins read
A A
python sqlite show tables
python sqlite create tables

Let’s use Python SQLite3 to create and show tables. SQLite is a lightweight, serverless, embedded database system that runs as part of our script or application. Following are some other features:

  1. Developed in C programming language and is open source.
  2. Supports SQL language.
  3. Writes data directly to a file on the filesystem.
  4. Little configuration required.
  5. Supports only a small set of datatypes: NULL, INTEGER, REAL, TEXT and BLOB.
  6. Ideal for very small datasets.
  7. Is not a substitute for a large complex DBMS like Oracle or SQL Server.

Let’s write some code to create a SQLite DB:

import sqlite3
con = sqlite3.connect('data/sample.db')
cur = con.cursor()

# Create table
cur.execute('''CREATE TABLE IF NOT EXISTS Playlist
              (createdate text, id integer, artist text, songTitle text, albumTitle text, duration text, songprice real)''')

#commit changes
con.commit()

# Close connection but commit changes before you do this
con.close()

Let’s explain what’s going on here:

  1. First import our sqlite3 library.
  2. sqlite3.connect() opens a connection to the SQLite database file supplied in the parameter. Our parameter is the path to the database file sample.db. The connect() method returns a Connection object which we store as con.
  3. con.cursor() returns an instance of class Cursor. This is important because class Cursor has the methods that we will use to execute queries. We store our object in cur.
  4. cur.execute() is what executes the SQL Statement. It accepts a SQL statement. In this case we are creating one table called Playlist if it doesn’t already exist.
  5. con.commit() commits the current transaction. If this is not called before the connection is closed changes to the data in the table will be lost. On this occasion it is not necessary because we are only creating a table. CREATE TABLE is a DDL statement which means that there is an implicit ‘commit’.
  6. con.close() closes the database connection. It is always good practice to close a database connection when it is no longer needed.

The above example will not return any output. If we want to know what tables already exist in the database we can execute the following query:

for row in cur.execute('''SELECT name FROM sqlite_master WHERE type='table' ORDER BY name'''):
    print(row)

#Output
#('Playlist',)

Every SQLite database contains a schema table that stores a record of every created table in the database. This table goes by the name sqlite_master or sqlite_schema table, for backwards compatibility. In the above code we simply query that table to discover what tables already exist in our SQLite database sample.db.

Following is our complete code:

import sqlite3
con = sqlite3.connect('data/sample.db')
cur = con.cursor()

# Create table
cur.execute('''CREATE TABLE IF NOT EXISTS Playlist
              (createdate text, id integer, artist text, songTitle text, albumTitle text, duration text, songprice real)''')

cur.execute('''CREATE TABLE IF NOT EXISTS Playlist2
              (createdate text, id integer, artist text, songTitle text, albumTitle text, duration text, songprice real)''')

for row in cur.execute('''SELECT name FROM sqlite_schema WHERE type='table' ORDER BY name'''):
    print(row) #shows two tables 
 
# Close connection
con.close()

con = sqlite3.connect('data/sample.db')
cur = con.cursor()

# Drop table
cur.execute('''DROP TABLE IF EXISTS Playlist2''')

for row in cur.execute('''SELECT name FROM sqlite_master WHERE type='table' ORDER BY name'''):
   print(row) #shows one table 

# Close connection
con.close()


#Output
#('Playlist',)
#('Playlist2',)
#('Playlist',)

So now you know how to use Python SQLite3 to create and show tables. In the next part of this tutorial we will explore how to INSERT and SELECT Rows from our SQLite table. Click HERE for Part 2.

Tags: databasesqlsqlite
Previous Post

Bar Plot with Python and seaborn

Next Post

Python sqlite3 Select and Insert

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy