增刪改
from pymysql import *
def main():
# 創(chuàng)建Connection連接
conn = connect(host='localhost',port=3306,database='jing_dong',user='root',password='mysql',charset='utf8')
# 獲得Cursor對(duì)象
cs1 = conn.cursor()
# 執(zhí)行insert語(yǔ)句,并返回受影響的行數(shù):添加一條數(shù)據(jù)
# 增加
count = cs1.execute('insert into goods_cates(name) values("硬盤")')
#打印受影響的行數(shù)
print(count)
count = cs1.execute('insert into goods_cates(name) values("光盤")')
print(count)
# # 更新
# count = cs1.execute('update goods_cates set name="機(jī)械硬盤" where name="硬盤"')
# # 刪除
# count = cs1.execute('delete from goods_cates where id=6')
# 提交之前的操作玫鸟,如果之前已經(jīng)之執(zhí)行過多次的execute导绷,那么就都進(jìn)行提交
conn.commit()
# 關(guān)閉Cursor對(duì)象
cs1.close()
# 關(guān)閉Connection對(duì)象
conn.close()
if name == 'main':
main()
查詢一行數(shù)據(jù)
from pymysql import *
def main():
# 創(chuàng)建Connection連接
conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
# 獲得Cursor對(duì)象
cs1 = conn.cursor()
# 執(zhí)行select語(yǔ)句,并返回受影響的行數(shù):查詢一條數(shù)據(jù)
count = cs1.execute('select id,name from goods where id>=4')
# 打印受影響的行數(shù)
print("查詢到%d條數(shù)據(jù):" % count)
for i in range(count):
# 獲取查詢的結(jié)果
result = cs1.fetchone()
# 打印查詢的結(jié)果
print(result)
# 獲取查詢的結(jié)果
# 關(guān)閉Cursor對(duì)象
cs1.close()
conn.close()
if name == 'main':
main()
查詢多行數(shù)據(jù)
from pymysql import *
def main():
# 創(chuàng)建Connection連接
conn = connect(host='localhost',port=3306,user='root',password='mysql',database='jing_dong',charset='utf8')
# 獲得Cursor對(duì)象
cs1 = conn.cursor()
# 執(zhí)行select語(yǔ)句屎飘,并返回受影響的行數(shù):查詢一條數(shù)據(jù)
count = cs1.execute('select id,name from goods where id>=4')
# 打印受影響的行數(shù)
print("查詢到%d條數(shù)據(jù):" % count)
# for i in range(count):
# # 獲取查詢的結(jié)果
# result = cs1.fetchone()
# # 打印查詢的結(jié)果
# print(result)
# # 獲取查詢的結(jié)果
result = cs1.fetchall()
print(result)
# 關(guān)閉Cursor對(duì)象
cs1.close()
conn.close()
if name == 'main':
main()