pymysql操作mysql數(shù)據(jù)庫
-
安裝pymysql
pip install pymysql
pymysql操作數(shù)據(jù)庫
1.連接數(shù)據(jù)庫 使用Connect方法連接數(shù)據(jù)庫 pymysql.Connections.Connection(host=None, user=None, password='', database=None, port=0, charset='') 參數(shù)說明: host – 數(shù)據(jù)庫服務(wù)器所在的主機。 user – 登錄用戶名。 password – 登錄用戶密碼。 database – 連接的數(shù)據(jù)庫。 port – 數(shù)據(jù)庫開放的端口。(默認: 3306) charset – 連接字符集。 返回值: 返回連接對象
例子: link = pymysql.Connect(host='localhost', port=3306, user='root', password='123456', db='shop', charset='utf8')
方法 | 說明 |
---|---|
begin() | 開啟事務(wù) |
commit() | 提交事務(wù) |
cursor(cursor=None) | 創(chuàng)建一個游標(biāo)用來執(zhí)行sql語句 |
rollback() | 回滾事務(wù) |
close() | 關(guān)閉連接 |
select_db(db) | 選擇數(shù)據(jù)庫 |
- 連接對象方法
2.創(chuàng)建游標(biāo)
cursor = link.cursor() print(cursor.rowcount) #打印受影響行數(shù)
方法 | 說明 |
---|---|
close() | 關(guān)閉游標(biāo) |
execute(query, args=None) | 執(zhí)行單條語句,傳入需要執(zhí)行的語句,是string類型;同時可以給查詢傳入?yún)?shù),參數(shù)可以是tuple、list或dict。執(zhí)行完成后,會返回執(zhí)行語句的影響行數(shù)。 |
fetchone() | 取一條數(shù)據(jù) |
fetchmany(n) | 取多條數(shù)據(jù) |
fetchall() | 取所有數(shù)據(jù) |
3.執(zhí)行sql語句
# 執(zhí)行sql語句
sql = 'select * from user1'
# 執(zhí)行完sql語句,返回受影響的行數(shù) num = cursor.execute(sql)
4.獲取結(jié)果集 result1 = cursor.fetchone() print(result1)
5.關(guān)閉連接 cursor.close() link.close()
pymysql中事務(wù)處理
pymysql默認是沒有開啟自動提交事務(wù),所以我們?nèi)绻M行增、刪、改,就必須手動提交或回滾事務(wù)。
sql = 'delete from user where id=%s' % user_id
?
# 如果要執(zhí)行增刪改語句的時候,下面的就是固定格式
try:
cursor.execute(sql)
# 如果全部執(zhí)行成功,提交事務(wù)
link.commit()
print(cursor.lastrowid) #獲取最后插入記錄的自增id號
except Exception as e:
print(e)
link.rollback()
finally:
cursor.close()
link.close()
案例
使用pymysql向goods表中添加一條數(shù)據(jù):文章來源:http://www.zghlxwxcb.cn/news/detail-783414.html
from pymysql import *
?
def main():
# 創(chuàng)建connection連接
conn = connect(host='localhost', port=3306, database='shop', user='root',
? ? ? ? password='root', charset='utf8')
# 獲取cursor對象
cs1 = conn.cursor()
# 執(zhí)行sql語句
query = "insert into goods(id,name,price,num) values(%s,%s,%s,%s)"
cs1.execute(query,(4,'蒙牛酸奶',13.9,88))
# 提交之前的操作,如果之前已經(jīng)執(zhí)行多次的execute,那么就都進行提交
conn.commit()
# 關(guān)閉cursor對象
cs1.close()
# 關(guān)閉connection對象
conn.close()
if __name__ == '__main__':
main()
當(dāng)然也可以刪除、查詢、修改表中的數(shù)據(jù),但是無論是怎么操作,都需要創(chuàng)建連接并在結(jié)束的時候關(guān)閉連接對象。文章來源地址http://www.zghlxwxcb.cn/news/detail-783414.html
到了這里,關(guān)于DevOps系列之 Python操作數(shù)據(jù)庫的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!