日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python怎么操作mysql

pymsql是python中操作mysql的模塊,其使用方法和MySQLdb幾乎相同。但目前pymysql支持python3.x,而MySQLdb不支持3.x版本。

我們提供的服務(wù)有:成都網(wǎng)站設(shè)計、成都做網(wǎng)站、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、湯旺ssl等。為1000+企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的湯旺網(wǎng)站制作公司

本文測試python版本:3.6。mysql版本:5.6.24

1.通過 pip 安裝 pymysql

進(jìn)入cmd,輸入:

pip install pymysql

按回車鍵,等待安裝完成。

2.測試連接

import pymysql  #導(dǎo)入 pymysql ,如果編譯未出錯,即表示 pymysql 安裝成功

3.pymysql操作

表結(jié)構(gòu)如下:

3.1查詢操作

import pymysql  #導(dǎo)入 pymysql
#打開數(shù)據(jù)庫連接
db= pymysql.connect(host="localhost",user="root",
     password="123456",db="test",port=3307)
# 使用cursor()方法獲取操作游標(biāo)
cur = db.cursor()
#1.查詢操作
# 編寫sql 查詢語句  user 對應(yīng)我的表名
sql = "select * from user"
try:
    cur.execute(sql)     #執(zhí)行sql語句
    results = cur.fetchall()    #獲取查詢的所有記錄
    print("id","name","password")
    #遍歷結(jié)果
    for row in results :
        id = row[0]
        name = row[1]
        password = row[2]
        print(id,name,password)
except Exception as e:
    raise e
finally:
    db.close()    #關(guān)閉連接

3.2插入操作

import pymysql
#2.插入操作
db= pymysql.connect(host="localhost",user="root",
     password="123456",db="test",port=3307)
# 使用cursor()方法獲取操作游標(biāo)
cur = db.cursor()
sql_insert ="""insert into user(id,username,password) values(4,'liu','1234')"""
try:
    cur.execute(sql_insert)
    #提交
    db.commit()
except Exception as e:
    #錯誤回滾
    db.rollback() 
finally:
    db.close()

3.3更新操作

#3.更新操作
db= pymysql.connect(host="localhost",user="root",
     password="123456",db="test",port=3307)
# 使用cursor()方法獲取操作游標(biāo)
cur = db.cursor()
sql_update ="update user set username = '%s' where id = %d"
try:
    cur.execute(sql_update % ("xiongda",3))  #像sql語句傳遞參數(shù)
    #提交
    db.commit()
except Exception as e:
    #錯誤回滾
    db.rollback() 
finally:
    db.close()

3.4刪除操作

import pymysql
#4.刪除操作
db= pymysql.connect(host="localhost",user="root",
     password="123456",db="test",port=3307)
# 使用cursor()方法獲取操作游標(biāo)
cur = db.cursor()
sql_delete ="delete from user where id = %d"
try:
    cur.execute(sql_delete % (3))  #像sql語句傳遞參數(shù)
    #提交
    db.commit()
except Exception as e:
    #錯誤回滾
    db.rollback() 
finally:
    db.close()

python學(xué)習(xí)網(wǎng),大量的免費python視頻教程,歡迎在線學(xué)習(xí)!


本文標(biāo)題:創(chuàng)新互聯(lián)Python教程:python怎么操作mysql
網(wǎng)站路徑:http://www.dlmjj.cn/article/ccsopdc.html