python將數(shù)據(jù)插入數(shù)據(jù)庫的代碼分享
python將數(shù)據(jù)插入數(shù)據(jù)庫的方法:
首先讀入數(shù)據(jù)并建立數(shù)據(jù)庫連接; 然后創(chuàng)建數(shù)據(jù)庫; 接著執(zhí)行插入數(shù)據(jù)語句,迭代讀取每行數(shù)據(jù); 最后關(guān)閉數(shù)據(jù)庫連接即可。比如現(xiàn)在我們要將如下Excel數(shù)據(jù)表格插入到MySQL數(shù)據(jù)庫中,該如何實(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ù)庫連接db = pymysql.connect(’localhost’,’root’,’1234’,’python_analysis’)#獲取游標(biāo)對象cursor = db.cursor()#創(chuàng)建數(shù)據(jù)庫,如果數(shù)據(jù)庫已經(jīng)存在,注意主鍵不要重復(fù),否則出錯try: cursor.execute(’create table catering_sale(num int primary key,date datetime, sale float )’)except: print(’數(shù)據(jù)庫已存在!’)#插入數(shù)據(jù)語句query = '''insert into catering_sale (num, date, sale) values (%s,%s,%s)'''#迭代讀取每行數(shù)據(jù)#values中元素有個類型的強(qiáng)制轉(zhuǎn)換,否則會出錯的#應(yīng)該會有其他更合適的方式,可以進(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ù)庫連接#如果沒有這些關(guān)閉操作,執(zhí)行后在數(shù)據(jù)庫中查看不到數(shù)據(jù)cursor.close()db.commit()db.close()#重新建立數(shù)據(jù)庫連接db = pymysql.connect(’localhost’,’root’,’1234’,’python_anylysis’)cursor = db.cursor()#查詢數(shù)據(jù)庫并打印內(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()
知識點(diǎn)擴(kuò)展:
數(shù)據(jù)庫連接池
數(shù)據(jù)庫的連接是昂貴的,一個連接要經(jīng)過TCP三次握手,四次揮手,而且一臺計算機(jī)的最大線程數(shù)也是有限的
數(shù)據(jù)庫連接池技術(shù)就是先創(chuàng)建好連接,再直接拿出來使用
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ù)庫的代碼分享的文章就介紹到這了,更多相關(guān)python如何將數(shù)據(jù)插入數(shù)據(jù)庫內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 如何對php程序中的常見漏洞進(jìn)行攻擊2. PHP循環(huán)與分支知識點(diǎn)梳理3. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能4. Ajax請求超時與網(wǎng)絡(luò)異常處理圖文詳解5. JavaWeb Servlet中url-pattern的使用6. 利用ajax+php實(shí)現(xiàn)商品價格計算7. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫的方法8. ASP中格式化時間短日期補(bǔ)0變兩位長日期的方法9. JSP之表單提交get和post的區(qū)別詳解及實(shí)例10. 利用FastReport傳遞圖片參數(shù)在報表上展示簽名信息的實(shí)現(xiàn)方法
