Pycharm编辑下 Python3 和mysql的交互

使用pycharm编辑器在python3与mysql进行交互,需要安装python扩展包pymysql,网友们需要注意,python3只能安装pymql,不能安装mysql-python包,只有Python2可以。

1、如何安装pymysql,有两种方式

(1)在pycharm编辑器中,[文件]-[设置]-[Project Interpreter]中点击加号,进行搜索安装

(2)使用cmd命令窗口,输入

pip install pymysql
进行安装,优先考虑第二种方法

安装完成后,可以在cmd窗口中 使用

pip show pymysql 

命令验证pymysql包是否安装成功。 

2、创建mysql数据库,创建students表

create table students(
id int auto_increment primary key,
sname varchar(10) not null
);
3、数据操作,添加score字段,插入一列信息

alter table students add score int;
insert into students(sname,score) values("郭靖","60");
4、python3 操作 MySQL

(1)插入数据代码

import pymysql

conn = pymysql.connect(host='localhost',port=3306,db='bgdgis',user='root',passwd='123456',charset='utf8')
cur = conn.cursor()
sql = "insert into students(sname,score) values('黄蓉','80')"
cur.execute(sql)
conn.commit()
cur.close()
conn.close()
(2)查询数据代码:

import pymysql

conn = pymysql.connect(host='localhost',port=3306,db='bgdgis',user='root',passwd='123456',charset='utf8')
cur = conn.cursor()
sql = "select sname,score from students"
cur.execute(sql)
# result = cur.fetchone()
result = cur.fetchall()
for data in result:
    print(data)
cur.close()
conn.close()
说明:fetchone() 执行查询语句时,获取查询结果集的第一个行数据,返回一个元祖。

         fetchall() 执行查询语句时,获取查询结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回

         







你可能感兴趣的:(Python)