এই টিউটোরিয়ালে, আমরা শিখব কিভাবে 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
উপসংহার
টিউটোরিয়ালটিতে আপনার কোন সন্দেহ থাকলে, মন্তব্য বিভাগে উল্লেখ করুন।