Python 连接 MySQL 数据库插入操作

aiofo2022-08-03  170

以下实例使用执行 SQL INSERT 语句向表 EMPLOYEE 插入记录:

#!/usr/bin/python 
# -*- coding: UTF-8 -*- 
import MySQLdb 
# 打开数据库连接 db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' ) 
# 使用cursor()方法获取操作游标  
cursor = db.cursor() 
# SQL 插入语句 
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,          
LAST_NAME, AGE, SEX, INCOME)          
VALUES ('Mac', 'Mohan', 20, 'M', 2000)""" 
try:    
# 执行sql语句    
cursor.execute(sql)    
# 提交到数据库执行    
db.commit() except:    
# Rollback in case there is any error    
db.rollback() 
# 关闭数据库连接 
db.close()

以上例子也可以写成如下形式:

#!/usr/bin/python 
# -*- coding: UTF-8 -*- 
import MySQLdb 
# 打开数据库连接 
db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' ) 
# 使用cursor()方法获取操作游标  cursor = db.cursor() 
# SQL 插入语句 
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \        
LAST_NAME, AGE, SEX, INCOME) \        
VALUES (%s, %s, %s, %s, %s )" % \        
('Mac', 'Mohan', 20, 'M', 2000) try:    
# 执行sql语句    cursor.execute(sql)    
# 提交到数据库执行    db.commit() except:    
# 发生错误时回滚    db.rollback() 
# 关闭数据库连接 
db.close()

实例:

以下代码使用变量向SQL语句中传递参数:

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



转载请注明原文地址:https://www.aiofo.com/read-360.html