python中mysql的增刪改查

增刪改

from pymysql import *

def main():
# 創(chuàng)建Connection連接
conn = connect(host='localhost',port=3306,database='jing_dong',user='root',password='mysql',charset='utf8')
# 獲得Cursor對象
cs1 = conn.cursor()
# 執(zhí)行insert語句,并返回受影響的行數(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="機械硬盤" where name="硬盤"')
# # 刪除
# count = cs1.execute('delete from goods_cates where id=6')

# 提交之前的操作,如果之前已經(jīng)之執(zhí)行過多次的execute,那么就都進行提交
conn.commit()

# 關(guān)閉Cursor對象
cs1.close()
# 關(guān)閉Connection對象
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對象
cs1 = conn.cursor()
# 執(zhí)行select語句,并返回受影響的行數(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對象
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對象
cs1 = conn.cursor()
# 執(zhí)行select語句,并返回受影響的行數(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對象
cs1.close()
conn.close()

if name == 'main':
main()

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容