欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

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

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

在這里插入圖片描述

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

要先安裝一個(gè)庫pymysql

import pymysql as mysql

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

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

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

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

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

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

"""在這個(gè)文件里,完成python操縱mysql的模塊化實(shí)現(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")

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

總結(jié)

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

相關(guān)文章

最新評(píng)論