Python操作mysql数据库
先来个例子
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","root","","dj" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
#cursor.execute("SELECT VERSION()")
cursor.execute("select * from blog_article")
# 使用 fetchone() 方法获取一条数据
#data = cursor.fetchone()
#多行
data = cursor.fetchmany()
#print "Database version : %s " % data
print "article list : %s " % data
#print data
"""
article list : (5L, 'Django ??MySQL???1', 'test', datetime.date(2017, 5, 3), datetime.datetime(2017, 5, 3, 3, 37, 4, 603608))
"""
# 关闭数据库连接
db.close()
<pre>
=测试给小伙伴的例子=
<pre>
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
In [3]: conn = MySQLdb.connect(host='localhost',port = 3306,user='root', passwd='',db ='dj',)
In [4]: cur = conn.cursor()
In [6]: cur.execute("select * from blog_article ")
Out[6]: 1L
In [7]: evan=cur.execute("select * from blog_article ")
In [8]: print evan
1
In [11]: cur = conn.cursor()
In [12]: cur.execute("select * from blog_article ")
Out[12]: 1L
In [13]: cur.fetchone()
Out[13]:
(5L,
'Django ??MySQL???1',
'test',
datetime.date(2017, 5, 3),
datetime.datetime(2017, 5, 3, 3, 37, 4, 603608))
In [14]: cur.fetchmany()
Out[14]: ()
In [15]: cur.execute("select * from blog_article ")
Out[15]: 1L
In [16]: cur.fetchmany()
Out[16]:
((5L,
'Django ??MySQL???1',
'test',
datetime.date(2017, 5, 3),
datetime.datetime(2017, 5, 3, 3, 37, 4, 603608)),)
创建数据库表
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 如果数据表已经存在使用 execute() 方法删除表。
cursor.execute("DROP TABLE IF EXISTS 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)
# 关闭数据库连接
db.close()
数据库插入操作
以下实例使用执行 SQL INSERT 语句向表 EMPLOYEE 插入记录:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用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()
数据库查询操作
python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。 fetchone(): 该方法获取下一个查询结果集。结果集是一个对象 fetchall():接收全部的返回结果行. rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#查询EMPLOYEE表中salary(工资)字段大于1000的所有数据:
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
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:
print "Error: unable to fecth data"
# 关闭数据库连接
db.close()
数据库更新操作
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#更新操作用于更新数据表的的数据,以下实例将 EMPLOYEE 表中的 SEX 字段为 'M' 的 AGE 字段递增 1:
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 更新语句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
# 执行SQL语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 发生错误时回滚
db.rollback()
# 关闭数据库连接
db.close()