Python连接MySQL数据库操作
Python操作MySQL有两个模块可以实现.
MySQLdb模块和mysql.connector模块.
MySQLdb模块:
# encoding: utf-8
#!/usr/bin/python
import MySQLdb
#步骤一、打开数据库连接
db = MySQLdb.connect(“localhost”,”testuser”,”test123″,”TESTDB”
)
db.select_db(‘test’) #改变数据库
#步骤二、 使用cursor()方法获取操作游标
cursor = db.cursor()
#步骤三、执行操作.
执行SQL:插入数据,DDL操作类似
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Mac', 'Mohan', 20, 'M', 2000)
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# Rollback in case there is any error …[获取更多]