用python實現(xiàn)操縱mysql數(shù)據(jù)庫插入
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)建一個游標
cur = db.cursor()
# 用游標cur執(zhí)行一個數(shù)據(jù)庫的查詢命令,用result來接收返回值
result = cur.execute(sql)
print(result)
# 提交當前事務,才會提交到數(shù)據(jù)庫,可以嘗試只執(zhí)行上面的代碼,看看結(jié)果
db.commit()
# 關(guān)閉游標對象
cur.close()
# 關(guān)閉連接
db.close()
關(guān)于pymysql.connect()方法相關(guān)的對象還有方法,可以看看這位大佬的文章,里面有相關(guān)參數(shù)和返回值什么的
2.在完成過程實現(xiàn)后,嘗試模塊化設計
"""在這個文件里,完成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)文章希望大家以后多多支持腳本之家!
- python數(shù)據(jù)庫批量插入數(shù)據(jù)的實現(xiàn)(executemany的使用)
- python將數(shù)據(jù)插入數(shù)據(jù)庫的代碼分享
- 在python中使用pymysql往mysql數(shù)據(jù)庫中插入(insert)數(shù)據(jù)實例
- python的mysql數(shù)據(jù)庫建立表與插入數(shù)據(jù)操作示例
- python讀取word文檔,插入mysql數(shù)據(jù)庫的示例代碼
- 使用python讀取csv文件快速插入數(shù)據(jù)庫的實例
- python數(shù)據(jù)庫操作常用功能使用詳解(創(chuàng)建表/插入數(shù)據(jù)/獲取數(shù)據(jù))
- python向MySQL數(shù)據(jù)庫插入數(shù)據(jù)的操作方法
相關(guān)文章
Python正則表達式高效處理文本數(shù)據(jù)的秘訣輕松掌握
當談到文本處理和搜索時,正則表達式是Python中一個強大且不可或缺的工具,正則表達式是一種用于搜索、匹配和處理文本的模式描述語言,可以在大量文本數(shù)據(jù)中快速而靈活地查找、識別和提取所需的信息,2023-11-11
Pycharm配置opencv與numpy的實現(xiàn)
本文總結(jié)了兩種方法來導入opencv與numpy包,第一種是直接在Pycharm中導入兩個包,第二種是在官網(wǎng)下載相關(guān)文件進行配置,感興趣的小伙伴們可以參考一下2021-07-07
python爬取bilibili網(wǎng)頁排名,視頻,播放量,點贊量,鏈接等內(nèi)容并存儲csv文件中
這篇文章主要介紹了python爬取bilibili網(wǎng)頁排名,視頻,播放量,點贊量,鏈接等內(nèi)容并存儲csv文件中,首先要了解html標簽,標簽有主有次,大致了解以一下,主標簽是根標簽,也是所有要爬取的標簽的結(jié)合體,需要的朋友可以參考一下2022-01-01
在ipython notebook中使用argparse方式
這篇文章主要介紹了在ipython notebook中使用argparse方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04

