इस ट्यूटोरियल में, हम सीखेंगे कि PostgreSQL . का उपयोग कैसे करें पायथन के साथ। ट्यूटोरियल में जाने से पहले आपको कुछ खास चीजों को इंस्टॉल करना होगा। आइए उन्हें स्थापित करें।
PostgreSQL स्थापित करें गाइड के साथ..
पायथन स्थापित करें PostgreSQL कनेक्शन और काम करने के लिए मॉड्यूल psycopg2। इसे स्थापित करने के लिए कमांड चलाएँ।
pip install psycopg2
अब, pgAdmin खोलें . और एक नमूना डेटाबेस बनाएँ। इसके बाद, डेटाबेस संचालन के साथ आरंभ करने के लिए नीचे दिए गए चरणों का पालन करें।
- psycopg2 मॉड्यूल आयात करें।
- डेटाबेस नाम, उपयोगकर्ता नाम और पासवर्ड को अलग-अलग चरों में संग्रहीत करें।
- psycopg2.connect(database=name,user=name, password=password) का उपयोग करके डेटाबेस से कनेक्शन बनाएं विधि।
- एक कर्सर ऑब्जेक्ट को SQL निष्पादित करने के लिए त्वरित करें आदेश।
- क्वेरी बनाएं और उन्हें cursor.execute(query) . के साथ निष्पादित करें विधि।
- और cursor.fetchall() का उपयोग करके जानकारी प्राप्त करें यदि उपलब्ध हो तो विधि।
- कनेक्शन बंद करें connection.close() . का उपयोग करके विधि।
उदाहरण
# importing the psycopg2 module
import psycopg2
# storing all the information
database = 'testing'
user = 'postgres'
password = 'C&o%Z?bc'
# connecting to the database
connection = psycopg2.connect(database=database, user=user, password=password)
# instantiating the cursor
cursor = connection.cursor()
# query to create a table
create_table = "CREATE TABLE testing_members (id SERIAL PRIMARY KEY, name VARCH
25) NOT NULL)"
# executing the query
cursor.execute(create_table)
# sample data to populate the database table
testing_members = ['Python', 'C', 'JavaScript', 'React', 'Django']
# query to populate the table testing_members
for testing_member in testing_members:
populate_db = f"INSERT INTO testing_members (name) VALUES ('{testing_member
cursor.execute(populate_db)
# saving the changes to the database
connection.commit()
# query to fetch all
fetch_all = "SELECT * FROM testing_members"
cursor.execute(fetch_all)
# fetching all the rows
rows = cursor.fetchall()
# printing the data
for row in rows:
print(f"{row[0]} {row[1]}")
# closing the connection
connection.close() आउटपुट
यदि आप उपरोक्त कोड चलाते हैं, तो आपको निम्न परिणाम प्राप्त होंगे।
1 Python 2 C 3 JavaScript 4 React 5 Django
निष्कर्ष
यदि आपको ट्यूटोरियल में कोई संदेह है, तो उनका टिप्पणी अनुभाग में उल्लेख करें।