20200204python連接數(shù)據(jù)庫
1、安裝python驅(qū)動(dòng)
pip3 install pymysql
2、數(shù)據(jù)庫操作命令
http://www.rzrgm.cn/UncleYong/p/7753188.html
創(chuàng)建數(shù)據(jù)庫設(shè)置字符集create database qzcsbj CHARACTER SET utf8;
打開創(chuàng)建的數(shù)據(jù)庫:use qzcsbj;
創(chuàng)建表:create table tablename (id int(5),name varchar(255),sex int(5),ega in(5));
查詢表結(jié)構(gòu):desc tablename;
插入數(shù)據(jù):insert users(id,name,sex,ega) values(1,'qzcsbj1',0,20),(2,'qzcsbj2',1,25),(3,'qzcsbj3',0,22),(4,'qzcsbj4',0,21);
3、連接測試
查詢 端口mysql>show global variables like 'port';
import pymysql
from pymysql.cursors import DictCursor
coon = pymysql.connect(host='192.168.72.128',port=3306,user='root',passwd='123456',db='mysql',charset='utf8') # 創(chuàng)建數(shù)據(jù)庫連接
cur = coon.cursor(DictCursor) # 建立游標(biāo),指定游標(biāo)類型,返回字典
sql='select * from user limit 2;' # 操作語句,只查詢前兩行
cur.execute(sql) # 執(zhí)行sql語句
res = cur.fetchall() # 獲取查詢的所有結(jié)果
print(res) # 打印結(jié)果
cur.close() # 關(guān)閉游標(biāo)
coon.close() # 關(guān)閉連接

浙公網(wǎng)安備 33010602011771號(hào)