Commit 782e3867 by rakesh.pv

this is complete crud operation with python : mongo and postgres

parents
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N806" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/crud_py_mongo_postgre.iml" filepath="$PROJECT_DIR$/.idea/crud_py_mongo_postgre.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
# CodeStream ignored files
/../../crud_pgl_fastapi\.idea/codestream.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CodeStream">
<option name="webViewContext" value="{&quot;chatProviderAccess&quot;:&quot;strict&quot;,&quot;currentTeamId&quot;:&quot;&quot;,&quot;currentStreamId&quot;:&quot;&quot;,&quot;pullRequestCheckoutBranch&quot;:false,&quot;isRepositioning&quot;:false,&quot;onboardStep&quot;:0,&quot;panelStack&quot;:[&quot;landing-redirect&quot;],&quot;hasFocus&quot;:false,&quot;channelFilter&quot;:&quot;all&quot;,&quot;channelsMuteAll&quot;:false,&quot;codemarkFileFilter&quot;:&quot;all&quot;,&quot;codemarkTypeFilter&quot;:&quot;all&quot;,&quot;codemarkTagFilter&quot;:&quot;all&quot;,&quot;codemarkBranchFilter&quot;:&quot;all&quot;,&quot;codemarkAuthorFilter&quot;:&quot;all&quot;,&quot;codemarksFileViewStyle&quot;:&quot;inline&quot;,&quot;codemarksShowArchived&quot;:false,&quot;codemarksShowResolved&quot;:false,&quot;codemarksWrapComments&quot;:false,&quot;showFeedbackSmiley&quot;:true,&quot;route&quot;:{&quot;name&quot;:&quot;newUserEntry&quot;,&quot;params&quot;:{}},&quot;spatialViewShowPRComments&quot;:false,&quot;currentPullRequestNeedsRefresh&quot;:{&quot;needsRefresh&quot;:false,&quot;providerId&quot;:&quot;&quot;,&quot;pullRequestId&quot;:&quot;&quot;},&quot;__teamless__&quot;:{&quot;selectedRegion&quot;:&quot;us&quot;},&quot;sessionStart&quot;:1674749537523}" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.10 (crud_py_mongo_postgre)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (crud_py_mongo_postgre)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/crud_pgl_fastapi.iml" filepath="$PROJECT_DIR$/.idea/crud_pgl_fastapi.iml" />
</modules>
</component>
</project>
\ No newline at end of file
from scripts.core.services.app import crud_operation_mongodb, crud_operations_postgresql
print("Welcome to Python Crud operations \nchoose your db\n"
"1.MongoDB\n"
"2.PostgreSQL\n")
choice = int(input("Enter your choice: "))
if choice == 1:
crud_operation_mongodb()
if choice == 2:
crud_operations_postgresql()
from pymongo import MongoClient
client = MongoClient('localhost', 27017) # 27017 is the default port number for mongodb
import psycopg2
def connect_db():
try:
connection = psycopg2.connect(user="root",
password="root",
host="127.0.0.1",
port="5432",
database="student")
return connection
except (Exception, psycopg2.Error) as error:
print("Failed to Connect to DB", error)
from scripts.core.config.mongodb_connection import client
import pymongo
def db_connect():
# create a connection
try:
connection = client
# create a database
db = connection['students']
except Exception as e:
print("Error ", e)
return db
def delete_many_document(collection):
try:
# delete more than one document
deleted_many = collection.delete_many({"pat_change": 33.3})
if deleted_many.acknowledged:
print("Documents deleted successfully")
else:
print("Documents deletion failed!")
except Exception as e:
print("Error ", e)
def delete_one_document(collection):
try:
# delete one document
deleted_one = collection.delete_one({"student name": "pv"})
if deleted_one.acknowledged:
print("One document deleted")
else:
print("Document deletion failed!")
except Exception as e:
print("Error ", e)
from scripts.core.handlers.mongo_db.insert_one_mongodb import data_from_user
def inserting_many(collection):
try:
# insert more than one document
print("------Inserting using insert_many------")
number_of_documents = int(input("Enter the number of documents to be inserted: "))
document_list = []
for i in range(0, number_of_documents):
print("----- Enter the details" + str(i + 1) + " -----\n")
document_list.append(data_from_user())
# inserting more than one document
inserted_many = collection.insert_many(document_list)
if inserted_many.acknowledged:
print(str(number_of_documents) + " documents inserted successfully!")
except Exception as e:
print("Error ", e)
def data_from_user():
full_name = input("Enter full name: ")
email= input("Enter email: ")
course_of_study = input("Enter course: ")
year = float(input("enter year: "))
gpa = float(input("Enter gap: "))
company_document = {
"full_name": full_name,
"company_name": email,
"course_of_study": course_of_study,
"year": year,
"gpa": gpa
}
return company_document
def inserting_one(collection):
try:
# insert one document
print("------Inserting using insert_one------")
# get data from user
data = data_from_user()
# inserting one document
inserted_one = collection.insert_one(data)
if inserted_one.acknowledged:
print("One document inserted successfully!")
else:
print("One document insertion failed!")
except Exception as e:
print("Error ", e)
def finding_one(collection):
try:
# find one document
print(list(collection.find({}, {"fullname": 1, "_id": 0, "email": "jdoe@x.edu.ng"})))
except Exception as e:
print("Error ", e)
def finding_many(collection):
try:
# find one document
print(collection.find_one())
except Exception as e:
print("Error ", e)
def update_one_document(collection):
try:
# update one
updated_one = collection.update_one({'email': "123@gmail,com."},
)
if updated_one.matched_count == 1:
print("One document updated!")
else:
print("Updating one document failed!")
except Exception as e:
print("Error ", e)
def update_many_document(collection):
try:
# update many
updated_many = collection.update_many({}, {"$set": {"pat_change": 3.6}})
if updated_many.matched_count != 0:
print("Documents updated Successfully!")
else:
print("Updating documents failed!")
except Exception as e:
print("Error ", e)
def delete_row(connection):
try:
cursor = connection.cursor()
print("------DELETE OPERATION------\n")
license_no = input("Enter the license no")
delete_data = f'DELETE FROM tbl_company WHERE license_no={license_no}'
cursor.execute(delete_data)
connection.commit()
print("Row deleted successfully!")
except Exception as e:
print("Error ", e)
def data_from_user():
company_license_no = input("Enter the company license no: ")
company_name = input("Enter the company name: ")
market_cap = input("Enter the market capital: ")
revenue_change = input("Enter the revenue change: ")
pat_change = input("Enter the pat change: ")
company_document = (company_license_no, company_name, market_cap, revenue_change, pat_change)
return company_document
from scripts.core.handlers.get_data_postgresql import data_from_user
def insert(connection):
cursor = connection.cursor()
print("------INSERT OPERATION------\n")
insert_table = "INSERT INTO tbl_company(license_no, company_name, market_cap,revenue_change, pat_change) VALUES(" \
"%s,%s,%s,%s,%s)"
row_value = data_from_user()
cursor.execute(insert_table, row_value)
connection.commit()
count = cursor.rowcount
print(count, "Record inserted successfully into tbl_company table")
def read_data(connection):
try:
cursor = connection.cursor()
print("------SELECT OPERATION------\n")
view_data = "SELECT * FROM tbl_company"
cursor.execute(view_data)
company_records = cursor.fetchall()
print("Each row and it's columns values")
for row in company_records:
print("license_no = ", row[0])
print("company_name = ", row[1])
print("market_cap = ", row[2])
print("revenue_change = ", row[3])
print("pat_change = ", row[4], "\n")
except Exception as e:
print("Error ", e)
def update_row(connection):
try:
cursor = connection.cursor()
print("------UPDATE OPERATION------\n")
license_no = input("Enter the license no")
print("Choose the field you want to update\n"
"1.company_name\n"
"2.market_cap\n"
"3.revenue_change\n"
"4.pat_change\n")
field_choice = int(input("Enter your choice: "))
if field_choice == 1:
update_data = input("Enter the data: ")
update_query = f'update tbl_company SET company_name ={update_data} where license_no={license_no}'
else:
if field_choice == 2:
field_to_update = "market_cap"
elif field_choice == 3:
field_to_update = "revenue_change"
elif field_choice == 4:
field_to_update = "pat_change"
update_data = input("Enter the data: ")
update_query = f'UPDATE tbl_company SET {field_to_update}={update_data} WHERE license_no={license_no}'
cursor.execute(update_query)
connection.commit()
print("Row updated successfully!")
except Exception as e:
print("Error ", e)
from scripts.core.config.postgres_connection import connect_db
from scripts.core.database.mongodb import db_connect
from scripts.core.handlers.mongo_db.delete_many_mongodb import delete_many_document
from scripts.core.handlers.mongo_db.delete_one_mongodb import delete_one_document
from scripts.core.handlers.mongo_db.read_one_mongodb import finding_one, finding_many
from scripts.core.handlers.mongo_db.insert_one_mongodb import inserting_one
from scripts.core.handlers.mongo_db.insert_many_mongodb import inserting_many
from scripts.core.handlers.mongo_db.update_one_mongodb import update_one_document
from scripts.core.handlers.mongo_db.updatw_many_mongodb import update_many_document
from scripts.core.handlers.posgres_db.delete_postgresql import delete_row
from scripts.core.handlers.posgres_db.insert_postgresql import insert
from scripts.core.handlers.posgres_db.read_data_postgresql import read_data
from scripts.core.handlers.posgres_db.update_postgresql import update_row
def crud_operation_mongodb():
try:
choice = int(input(
" enter which operation to perform\n0.display many\n1.display one\2.insert one\n3.insert many\n4.delete one\n5.delete many\n6.update one \n7. update many"))
# create a db connection
db = db_connect()
# create a collection
collection = db['students_collection']
if choice == 0:
finding_many(collection)
if choice == 1:
finding_one(collection)
if choice == 2:
inserting_one(collection)
if choice == 3:
inserting_many(collection)
if choice == 4:
delete_one_document(collection)
if choice == 5:
delete_many_document(collection)
if choice == 6:
update_one_document(collection)
if choice == 7:
update_many_document(collection)
except Exception as e:
print("Error-", e)
finally:
print("end")
def crud_operations_postgresql():
try:
postgresql_connection = connect_db()
cursor = postgresql_connection.cursor()
# checking if the table exists
cursor.execute(f"SELECT * FROM information_schema.tables WHERE table_name = 'tbl_company'")
if cursor.fetchone():
print("Table Already Exists!")
else:
postgres_create_query = """CREATE TABLE tbl_company (license_no INT,
company_name CHAR(50) NOT NULL,
market_cap INT NOT NULL,
revenue_change INT NOT NULL,
pat_change INT NOT NULL,
PRIMARY KEY( license_no ))"""
cursor.execute(postgres_create_query)
postgresql_connection.commit()
print("Table Created!")
# inserting records in the table
insert(postgresql_connection)
# read or selecting the data in the table
read_data(postgresql_connection)
# updating data in the table based on the license number user entered
update_row(postgresql_connection)
# deleting data in the table based on the license number user entered
delete_row(postgresql_connection)
except Exception as e:
print("Error-", e)
finally:
print("end")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment