(我的情况是:python安装在Windows系统下,MySQL安装在Linux系统下。)
1、导入pip包管理器(Windows下已经默认安装了,Linux下需要自行安装。)
2、安装pymysql驱动。pip install pymysql
3、导入驱动
>>> import pymysql
4、创建连接
conn=pymysql.connect(host="192.168.220.137",port=3306,user="root",password="redhat",db="H",charset="utf8")
如果提示以下错误:MySQL拒绝远程访问
(1130, "Host '192.168.220.1' is not allowed to connect to this MySQL server")
可以通过以下方法解决:
MySQL > use mysql;
MySQL [mysql]> update user set host='%' where user='root';
ERROR 1062 (23000): Duplicate entry '%-root' for key 'PRIMARY' #错误提示可以忽略
MySQL [mysql]> flush privileges;
5、获取游标对象
cursor=conn.cursor()
6、执行SQL cursor.execute("SQL") #如果是增删改,返回遂改的行数。如果是select,需要执行下一步
7、cursor.fetchall() '''返回多条数据,返回值为元组''' /cursor.fetchone() #返回一组数据,返回值是元组
提交事务:conn.commit()