亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

用python實現(xiàn)操縱mysql數(shù)據(jù)庫插入

 更新時間:2022年01月23日 09:01:55   作者:抹茶好喝  
大家好,本篇文章主要講的是用python實現(xiàn)操縱mysql數(shù)據(jù)庫插入,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下

python操縱mysql數(shù)據(jù)庫,向一個表中插入一條新的記錄。

pycahrm提供一個很好的功能,在右邊上面,可以連接數(shù)據(jù)庫,并在里面手動操作數(shù)據(jù)庫,連接步驟略過。

1.先看下表的結(jié)構(gòu),一個car表

在這里插入圖片描述

1.python過程實現(xiàn)

要先安裝一個庫pymysql

import pymysql as mysql

# 連接到數(shù)據(jù)庫,.connect()返回一個connection對象
db = mysql.connect(host="localhost", port=3306, user="root", passwd="123456", db="testcar")

# SQL語句,冒號str是類型提示
sql: str = "insert into testcar.car (carid, brand, in_time, out_time) " \
           "VALUES ('987','寶馬','2012','2015')"

# 用db(connection對象)創(chuàng)建一個游標(biāo)
cur = db.cursor()
# 用游標(biāo)cur執(zhí)行一個數(shù)據(jù)庫的查詢命令,用result來接收返回值
result = cur.execute(sql)
print(result)

# 提交當(dāng)前事務(wù),才會提交到數(shù)據(jù)庫,可以嘗試只執(zhí)行上面的代碼,看看結(jié)果
db.commit()
# 關(guān)閉游標(biāo)對象
cur.close()
# 關(guān)閉連接
db.close()

關(guān)于pymysql.connect()方法相關(guān)的對象還有方法,可以看看這位大佬的文章,里面有相關(guān)參數(shù)和返回值什么的

2.在完成過程實現(xiàn)后,嘗試模塊化設(shè)計

"""在這個文件里,完成python操縱mysql的模塊化實現(xiàn)"""

import pymysql as mysql


# 連接到數(shù)據(jù)庫
def connect(db_name):
    con = mysql.connect(host="localhost", port=3306, user="root", passwd="123456", db=db_name)
    return con


# 向表中插入一條記錄
def insert(sql, db_name):
    con = connect(db_name)
    cur = con.cursor()
    result = cur.execute(sql)
    con.commit()
    cur.close()
    con.close()
    if result == 1:
        print("執(zhí)行成功!")
    return

然后在main.py中調(diào)用

# main.py
import pmysql

sql: str = "insert into testcar.car (carid, brand, in_time, out_time) " \
           "VALUES ('asasa','法拉利','2010','2012')"

if __name__ == "__main__":
    pmysql.insert(sql, "testcar")

到此能實現(xiàn)表的插入操作了,其他的增刪查改操作也就大同小異了

總結(jié)

到此這篇關(guān)于用python實現(xiàn)操縱mysql數(shù)據(jù)庫插入的文章就介紹到這了,更多相關(guān)python mysql數(shù)據(jù)庫插入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論