参考: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
1 import pymysql 2 3 def test(): 4 try: 5 con = pymysql.connect(host="localhost", user="zxx", passwd="123xxx", db="world", port=3306, charset='utf8') 6 cursor = con.cursor() 7 8 cursor.execute("Select * from city limit 2, 5") 9 result = cursor.fetchall() 10 11 for record in result: 12 print(record) 13 14 cursor.close() 15 con.close() 16 17 except Exception as ex: 18 print(ex) 19 20 if __name__ == '__main__': 21 test()
运行结果:
E:programpythonmysql>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)