Search This Blog

Database connectivity 1 - Connect to database and Create table Hackerrank solutions Course ID:55195

  • 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_name, item_description, item_category and quantity_in_stock.
  • commit and close the connection .
  • Use the 'Test against custom imput' box to output the result for debugging. Use 'print(res)' to display the output.
Expected Output:
     None


Answer: 

#!/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
    sql1 = '''
    CREATE TABLE ITEMS(
        item_id INT(6) not null,
        item_name CHAR(20) not null,
        item_description CHAR(50),
        item_category CHAR(50),
        quantity_in_stock INT
        )
    '''
    cursor.execute(sql1)
    #commit connection 
    conn.commit()
    #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()

No comments:

Post a Comment

If you have any doubts, Please let us know.