কম্পিউটার

পাইথনে ডাটাবেস INSERT অপারেশন


যখন আপনি একটি ডাটাবেস টেবিলে আপনার রেকর্ড তৈরি করতে চান তখন এটি প্রয়োজন হয়৷

উদাহরণ

নিম্নলিখিত উদাহরণ, কর্মচারী টেবিলে একটি রেকর্ড তৈরি করতে SQL INSERT বিবৃতি কার্যকর করে −

#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
   LAST_NAME, AGE, SEX, INCOME)
   VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()
# disconnect from server
db.close()

এসকিউএল কোয়েরিগুলি গতিশীলভাবে −

তৈরি করতে উপরের উদাহরণটি নিম্নরূপ লেখা যেতে পারে
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
   LAST_NAME, AGE, SEX, INCOME) \
   VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
   ('Mac', 'Mohan', 20, 'M', 2000)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()
# disconnect from server
db.close()

উদাহরণ

নিম্নলিখিত কোড সেগমেন্ট হল এক্সিকিউশনের আরেকটি ফর্ম যেখানে আপনি সরাসরি প্যারামিটার পাস করতে পারেন −

..................................
user_id = "test123"
password = "password"
con.execute('insert into Login values("%s", "%s")' % \
   (user_id, password))
..................................

  1. MS SQL সার্ভারে ডাটাবেস মনিটরিং

  2. পাইথনে <> অপারেশন কি?

  3. কিভাবে একটি MySQL ডাটাবেসে একটি পাইথন টিপল সন্নিবেশ করান?

  4. কিভাবে একটি PostgreSql ডাটাবেসে একটি পাইথন টিপল সন্নিবেশ করান?