python操作Mysql数据库

来源:互联网 发布:bi软件安卓版 编辑:程序博客网 时间:2024/06/06 02:12

安装

下载安装:https://pypi.python.org/pypi/MySQL-python/1.2.5

操作

#!/usr/bin/python# -*- coding: UTF-8 -*-import MySQLdb# 打开数据库连接db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )# 使用cursor()方法获取操作游标 cursor = db.cursor()# 使用execute方法执行SQL语句cursor.execute("SELECT VERSION()")# 使用 fetchone() 方法获取一条数据库。data = cursor.fetchone()print "Database version : %s " % data# 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()
0 0
原创粉丝点击