Pycharm編輯下 Python3 和mysql的互動
阿新 • • 發佈:2019-01-25
使用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)插入資料程式碼
(2)查詢資料程式碼: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()
說明:fetchone() 執行查詢語句時,獲取查詢結果集的第一個行資料,返回一個元祖。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()
fetchall() 執行查詢語句時,獲取查詢結果集的所有行,一行構成一個元組,再將這些元組裝入一個元組返回