python將數(shù)據(jù)插入數(shù)據(jù)庫(kù)的代碼分享
python將數(shù)據(jù)插入數(shù)據(jù)庫(kù)的方法:
首先讀入數(shù)據(jù)并建立數(shù)據(jù)庫(kù)連接; 然后創(chuàng)建數(shù)據(jù)庫(kù); 接著執(zhí)行插入數(shù)據(jù)語(yǔ)句,迭代讀取每行數(shù)據(jù); 最后關(guān)閉數(shù)據(jù)庫(kù)連接即可。比如現(xiàn)在我們要將如下Excel數(shù)據(jù)表格插入到MySQL數(shù)據(jù)庫(kù)中,該如何實(shí)現(xiàn)呢?

實(shí)現(xiàn)代碼:
#導(dǎo)入需要使用到的數(shù)據(jù)模塊import pandas as pdimport pymysql#讀入數(shù)據(jù)filepath = ’E:_DataSetcatering_sale.xls’data = pd.read_excel(filepath)#建立數(shù)據(jù)庫(kù)連接db = pymysql.connect(’localhost’,’root’,’1234’,’python_analysis’)#獲取游標(biāo)對(duì)象cursor = db.cursor()#創(chuàng)建數(shù)據(jù)庫(kù),如果數(shù)據(jù)庫(kù)已經(jīng)存在,注意主鍵不要重復(fù),否則出錯(cuò)try: cursor.execute(’create table catering_sale(num int primary key,date datetime, sale float )’)except: print(’數(shù)據(jù)庫(kù)已存在!’)#插入數(shù)據(jù)語(yǔ)句query = '''insert into catering_sale (num, date, sale) values (%s,%s,%s)'''#迭代讀取每行數(shù)據(jù)#values中元素有個(gè)類型的強(qiáng)制轉(zhuǎn)換,否則會(huì)出錯(cuò)的#應(yīng)該會(huì)有其他更合適的方式,可以進(jìn)一步了解for r in range(0, len(data)): num = data.ix[r,0] date = data.ix[r,1] sale = data.ix[r,2] values = (int(num), str(date), float(sale)) cursor.execute(query, values)#關(guān)閉游標(biāo),提交,關(guān)閉數(shù)據(jù)庫(kù)連接#如果沒(méi)有這些關(guān)閉操作,執(zhí)行后在數(shù)據(jù)庫(kù)中查看不到數(shù)據(jù)cursor.close()db.commit()db.close()#重新建立數(shù)據(jù)庫(kù)連接db = pymysql.connect(’localhost’,’root’,’1234’,’python_anylysis’)cursor = db.cursor()#查詢數(shù)據(jù)庫(kù)并打印內(nèi)容cursor.execute(’’’select * from catering_sale’’’)results = cursor.fetchall()for row in results: print(row)#關(guān)閉cursor.close()db.commit()db.close()
知識(shí)點(diǎn)擴(kuò)展:
數(shù)據(jù)庫(kù)連接池
數(shù)據(jù)庫(kù)的連接是昂貴的,一個(gè)連接要經(jīng)過(guò)TCP三次握手,四次揮手,而且一臺(tái)計(jì)算機(jī)的最大線程數(shù)也是有限的
數(shù)據(jù)庫(kù)連接池技術(shù)就是先創(chuàng)建好連接,再直接拿出來(lái)使用
import mysql.connector,mysql.connector.pooling config={ 'host': 'localhost', 'port': '3306', 'user': 'root', 'password': 'password', 'database': 'demo' } try: pool=mysql.connector.pooling.MySQLConnectionPool(**config,pool_size=5) con=pool.get_connection() con.start_transaction() cursor = con.cursor() sql = 'INSERT INTO t_dept(deptno,dname,loc) VALUES(%s,%s,%s);' cursor.execute(sql, (70, 'SALES', 'HUBAI')) con.commit() except Exception as e: if 'con' in dir(): con.rollback() print(e) # do not need to close con
到此這篇關(guān)于python將數(shù)據(jù)插入數(shù)據(jù)庫(kù)的代碼分享的文章就介紹到這了,更多相關(guān)python如何將數(shù)據(jù)插入數(shù)據(jù)庫(kù)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Java如何基于反射機(jī)制獲取不同的類2. php模擬實(shí)現(xiàn)斗地主發(fā)牌3. asp判斷某個(gè)文件是否存在的函數(shù)4. IntelliJ IDEA安裝插件的方法步驟5. Android table布局開(kāi)發(fā)實(shí)現(xiàn)簡(jiǎn)單計(jì)算器6. 理解PHP5中static和const關(guān)鍵字7. ASP.NET泛型三之使用協(xié)變和逆變實(shí)現(xiàn)類型轉(zhuǎn)換8. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟9. .NET Core Web APi類庫(kù)內(nèi)嵌運(yùn)行的方法10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備