Python Database Connectivity: A Comprehensive Guide
☰Fullscreen
Table of Content:
1. Database Connectivity 1- Connect to Database and create Table
• Connect to a sample database 'SAMPLE.db'.
Hint: Use sqlite as the backend database, and sqlite3 DB-API.
• Create a connection cursor cursor.
• Create table ITEMS with attributes item_id, item_name, item_description, item_category and quantity_in_stock.
• commit and close the connection.
• Use the 'Test against custom input' box to output the result for debugging. Use 'print(res)' to display the output.
Solutions
#!/bin/python3 import sys import os import sqlite3 # Complete the following function: def main(): conn = sqlite3.connect('SAMPLE.db') #create connection cursor cursor = conn.cursor() #create table ITEMS using the cursor items = '''CREATE TABLE ITEMS(item_id INT,item_name CHAR(10),item_description CHAR(20),item_category CHAR(10),quantity_in_stock INT)''' #commit connection cursor.execute(items) #close connection conn.close() '''To test the code, no input is required''' if __name__ == "__main__": f = open(os.environ['OUTPUT_PATH'], 'w') res = main(); f.write(str(res) + "\n") f.close()
- Question 1: How do you access a database in Python?
- Question 2: How do you close a database connection in Python?
- Question 3: How do you handle errors when working with databases in Python?
- Question 4: How do you insert data into a database using Python DB-API?
- Question 5: How do you retrieve data from a query in Python using DB-API?
- Question 6: How do you execute a query in Python using DB-API?
- Question 7: What is a cursor in Python DB-API?
- Question 8: How do you connect to a database in Python?
- Question 9: What are some popular Python libraries for interacting with databases?
- Question 10: What is Python Database Connectivity (DB-API)?
- Question 11: How can you ensure data security when working with databases in Python?