কম্পিউটার টিউটোরিয়াল

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


यह तब आवश्यक होता है जब आप अपने रिकॉर्ड्स को एक डेटाबेस टेबल में बनाना चाहते हैं।

उदाहरण

निम्नलिखित उदाहरण, EMPLOYEE टेबल में एक रिकॉर्ड बनाने के लिए 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()

उपरोक्त उदाहरण को SQL क्वेरीज़ को डायनामिक रूप से बनाने के लिए निम्नानुसार लिखा जा सकता है −

#!/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 Server-এ ডেটাবেস মনিটরিং

  2. পাইথনে <> অপারেশনের আচরণ কী?

  3. পাইথন টাপলকে MySQL ডাটাবেসে ইনসার্ট করার পদ্ধতি

  4. পাইথন টাপলকে PostgreSQL ডাটাবেসে ইনসার্ট করার পদ্ধতি