python链接mysql的代码
用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 = rselect * 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()
import sys
import MySQLdbreload(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 = rselect * 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()
用python操作了mysql的数据库,发现非常的有趣,而且python操作mysql的方法非常的简单和快速,所以我把代码分享下大家,希望对大家学习有帮助本文来自: Rootexp
补充:Web开发 , Python ,