Python对MySQL数据库的操作,包括连接数据库、创建数据库、插入数据、查询数据。
1、连接mysql数据库
# -*-coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost", "root", "", "test")
# 参数为ip,用户名,密码,数据库
# 使用cursor()方法获取操作游标?什么叫游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
# 使用fetchone()
方法获取一条数据库。
data = cursor.fetchone()
# 格式化数据
print "Database version: %s " % data
print type(data)
# 关闭数据库连接
2、创建数据库表
# -*-coding: UTF-8 -*-import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost", "root", "", "mytest")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 如果数据表已经存在使用execute() 方法删除表。
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# 创建数据表SQL语句
sql= """CREATE TABLE Students(FIRST_NAME CHAR(10) NOT NULL,LAST_NAME CHAR(10),AGE INT,SEX CHAR(1),PHONE FLOAT )"""
cursor.execute(sql)
cursor.execute('show tables')
print cursor.fetchone()
# 关闭数据库连接
db.close()
3、插入数据到表格
# -*-coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost", "root", "", "test")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL插入语句
sql= """INSERT INTO Students(FIRST_NAME,LAST_NAME, AGE, SEX, PHONE)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()
4、查询数据
# -*-coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost", "root", "", "test")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
sql= "SELECT * FROM Students WHERE INCOME > '%d'" % (100)
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
fname= row[0]
lname= row[1]
age = row[2]
sex = row[3]
phone= row[4]
# 打印结果
print "fname=%s,lname=%s,age=%d,sex=%s,phone=%d" % \(fname, lname, age, sex, phone)
except:
print "Error: unable to fecthdata"
# 关闭数据库连接
db.close()