python通过MySQLdb模块链接数据库并添加数据完整代码演示

2022-04-24 00:00:00 模块 添加 演示

下面的python代码通过MySQLdb代码连接mysql数据库,通过sql语句添加数据,并演示了如何通过commit提交数据和rollback回滚操作

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()

相关文章