Python操作mysql之查询数据
#!/usr/bin/env python# -*- coding: utf-8 -*-
'''
Date:2016-11-08
Author:Bob
'''
import MySQLdb
def python_mysql_query():
#Open the database connection
db = MySQLdb.connect(host='localhost',user='ossec',passwd='mysql0123',db='ossec',port=3306, charset='utf8')
#Gets the operation cursor
cursor = db.cursor()
#SQL statement query
#sql = "select * from data where id < '%d'" % (5)
sql = "select * from data limit 5"
try:
#Execute the SQL statement
cursor.execute(sql)
#Receive all return results
results = cursor.fetchall()
#Traverse the print list
for i in results:
print i
except:
print "Error: unable to fecth data"
#Close the cursor
cursor.close()
#Close the database connection
db.close()
if __name__ == '__main__':
python_mysql_query()
页:
[1]