分享python链接mysql的代码
© laowang/ 2011-3-22 / 16:52
前几天我用python操作了mysql的数据库,发现非常的有趣,而且python操作mysql的方法非常的简单和快速,所以我把代码分享下大家,希望对大家学习有帮助。
import sys
import MySQLdb
reload(sys)
sys.setdefaultencoding('utf-8')
def getdata ():
try:
conn = MySQLdb.connect(host='localhost', user='root', passwd='root', db='test', port=3306, charset='utf8')
try:
cur = conn.cursor()
sql = r'select * from person'
cur.execute(sql)
allPerson = cur.fetchall()
finally:
cur.close()
conn.close()
except Exception, e:
print '数据库错误:', e
return
for rec in allPerson:
print rec[0],rec[1]
if __name__ == '__main__':
getdata()
© laowang/ 2011-3-22 / 16:52
前几天我用python操作了mysql的数据库,发现非常的有趣,而且python操作mysql的方法非常的简单和快速,所以我把代码分享下大家,希望对大家学习有帮助。
import sys
import MySQLdb
reload(sys)
sys.setdefaultencoding('utf-8')
def getdata ():
try:
conn = MySQLdb.connect(host='localhost', user='root', passwd='root', db='test', port=3306, charset='utf8')
try:
cur = conn.cursor()
sql = r'select * from person'
cur.execute(sql)
allPerson = cur.fetchall()
finally:
cur.close()
conn.close()
except Exception, e:
print '数据库错误:', e
return
for rec in allPerson:
print rec[0],rec[1]
if __name__ == '__main__':
getdata()