w3resource

Python: Create a SQLite database connection to a database that resides in the memory

Python SQLite Database: Exercise-2 with Solution

Write a Python program to create a SQLite database connection to a database that resides in the memory.

Sample Solution:

Python Code :

import sqlite3
try:
   sqlite_Connection = sqlite3.connect('temp.db')
   conn = sqlite3.connect(':memory:')
   print("\nMemory database created and connected to SQLite.")
   sqlite_select_Query ="select sqlite_version();"
   conn.execute(sqlite_select_Query)
   print("\nSQLite Database Version is: ", sqlite3.version)
   conn.close()
except sqlite3.Error as error:
   print("\nError while connecting to sqlite", error)
finally:
   if (sqlite_Connection):
       sqlite_Connection.close()
       print("\nThe SQLite connection is closed.")

Sample Output:

Memory database created and connected to SQLite.

SQLite Database Version is:  2.6.0

The SQLite connection is closed.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to create a SQLite database and connect with the database and print the version of the SQLite database.
Next: Write a Python program to connect a database and create a SQLite table within the database.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz


Python: Tips of the Day

Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value:

Example:

def tips_map_values(obj, fn):
  ret = {}
  for key in obj.keys():
    ret[key] = fn(obj[key])
  return ret
users = {
  'Owen': { 'user': 'Owen', 'age': 29 },
  'Eddie': { 'user': 'Eddie', 'age': 15 }
}

print(tips_map_values(users, lambda u : u['age'])) # {'Owen': 29, 'Eddie': 15}

Output:

{'Owen': 29, 'Eddie': 15}