您好,登錄后才能下訂單哦!
下面講講關(guān)于Python實(shí)現(xiàn)連接mysql后操作添加數(shù)據(jù)方法,文字的奧妙在于貼近主題相關(guān)。所以,閑話就不談了,我們直接看下文吧,相信看完P(guān)ython實(shí)現(xiàn)連接mysql后操作添加數(shù)據(jù)方法這篇文章你一定會有所受益。
1.Python3操作數(shù)據(jù)庫-添加數(shù)據(jù)操作
示例代碼:
#!/usr/bin/python
import pymysql;
'''
獲取mysql連接對象
'''
def open_connect():
try:
# 創(chuàng)建數(shù)據(jù)庫連接
dbconnect = pymysql.connect("localhost","root","","enquiry");
return dbconnect;
except:
print('打開連接異常');
return None;
'''
數(shù)據(jù)添加操作
'''
def insert_data(dbconnect,sql):
# 使用cursor()方法獲取操作游標(biāo)
cursor = dbconnect.cursor();
try:
# 執(zhí)行sql語句
cursor.execute(sql);
# 提交到數(shù)據(jù)庫執(zhí)行
dbconnect.commit();
return 1;
except:
# 如果發(fā)生錯(cuò)誤則回滾
dbconnect.rollback();
print('請檢查sql語法是否正確');
return 0;
'''
關(guān)閉數(shù)據(jù)庫連接
'''
def close_connect(dbconnect):
if dbconnect != None:
dbconnect.close();
# 1.打開連接
dbconnect = open_connect();
# 2.執(zhí)行添加數(shù)據(jù)操作
# 準(zhǔn)備sql語句
sql = '''INSERT INTO demo(name) VALUES ('Mohan')''';
if dbconnect != None:
res = insert_data(dbconnect,sql);
print(res);
close_connect(dbconnect);
示例截圖:
運(yùn)行截圖:
對于以上Python實(shí)現(xiàn)連接mysql后操作添加數(shù)據(jù)方法相關(guān)內(nèi)容,大家還有什么不明白的地方嗎?或者想要了解更多相關(guān),可以繼續(xù)關(guān)注我們的行業(yè)資訊板塊。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。