python连接mysql有两种方式
第一种:MySQLdb是官方未提供python模块时候的选择,后来mysql官方推出自己的Python模块。前者使用量比较大,文档较多,但似乎很久没有更新了,mysql提供的模块只支持到3.4(下载地址:https://dev.mysql.com/downloads/connector/python/);
第二种:使用python官方的,接下来重点讲解:
通过pip安装(cmd进入到python/Script目录):
pip install pymysql
连接:
#coding=utf-8 #导入pymysql的包 import pymysql import pymysql.cursors #获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库 #port 必须是数字不能为字符串 connection=pymysql.connect(host='localhost', user='root', password='123456', db='test', port=3307, charset='utf8') try: #获取一个游标 with connection.cursor() as cursor: sql='select * from user' cout=cursor.execute(sql) print("数量: "+str(cout)) for row in cursor.fetchall(): #print('%s\t%s\t%s' %row) #注意int类型需要使用str函数转义 print("ID: "+str(row[0])+' 名字: '+row[1]+" 性别: "+row[2]) connection.commit() finally: connection.close()
转载请注明:永盟博客 » 安装Python连接MySQL所需模块及连接方式