参考:http://www.blogjava.net/huyi2006/articles/247966.html

开发环境:win7_x64 + python3.4.3 + mysql5.6.23

准备:需要安装pymysql, 下载地址:https://codeload.github.com/PyMySQL/PyMySQL/zip/master

windows上安装:打开cmd命令窗口,执行:python setup.py install

linux上安装: 在终端执行(以root用户):python setup.py install

源码test.py

 import pymysql

 def test():
try:
con = pymysql.connect(host="localhost", user="zxx", passwd="123xxx", db="world", port=3306, charset='utf8')
cursor = con.cursor() cursor.execute("Select * from city limit 2, 5")
result = cursor.fetchall() for record in result:
print(record) cursor.close()
con.close() except Exception as ex:
print(ex) if __name__ == '__main__':
test()

运行结果:

E:\program\python\mysql>python test.py
(3, 'Herat', 'AFG', 'Herat', 186800)
(4, 'Mazar-e-Sharif', 'AFG', 'Balkh', 127800)
(5, 'Amsterdam', 'NLD', 'Noord-Holland', 731200)
(6, 'Rotterdam', 'NLD', 'Zuid-Holland', 593321)
(7, 'Haag', 'NLD', 'Zuid-Holland', 440900)
05-11 21:43