Python操作Mysql

已安装python


Python操作Mysql_第1张图片

已安装mysql


Python操作Mysql_第2张图片

安装Python MySQLdb库 yum install MySQL-python

Python操作Mysql_第3张图片

python脚本使用sql 语句操作数据库:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
importMySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","root","root","TESTDB")
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取一条数据库。
data = cursor.fetchone()
print"Database version : %s "% data
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
print'Drop EXIST Table EMPLOYEE!'
# 创建数据表SQL语句
sql ="""CREATE TABLE EMPLOYEE (
FIRST_NAME  CHAR(20) NOT NULL,
LAST_NAME  CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
print'create table EMPLYEE again.'
sql ="""INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
sql1 ="""INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', '  Pohan1', 22, 'M', 2000)"""
sql2 ="DELETE FROM EMPLOYEE WHERE AGE > '%d'"% (20)
sql3 ="select * FROM EMPLOYEE "
try:
# 执行sql语句
cursor.execute(sql)
print'insert Mohan-20 ok.'
cursor.execute(sql)
print'insert Pohan1-22 ok.'
# 执行SQL语句
cursor.execute(sql2)
print'delete Pohan1-22 ok.'
cursor.execute(sql3)
results = cursor.fetchall()
# 提交到数据库执行
db.commit()
forrowinresults:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 打印结果
print"fname=%s,lname=%s,age=%d,sex=%s,income=%d"% \
(fname, lname, age, sex, income)
except:
# Rollback in case there is any error
db.rollback()
print'insert data fail.'
# 关闭数据库连接
db.close()
Paste_Image.png
Paste_Image.png

你可能感兴趣的:(Python操作Mysql)