新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程: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ù)庫連接即可。

成都創(chuàng)新互聯(lián)從2013年創(chuàng)立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項目做網(wǎng)站、成都網(wǎng)站建設(shè)網(wǎng)站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元富陽做網(wǎng)站,已為上家服務(wù),為富陽各地企業(yè)和個人服務(wù),聯(lián)系電話:18980820575
比如現(xiàn)在我們要將如下Excel數(shù)據(jù)表格插入到MySQL數(shù)據(jù)庫中,該如何實現(xiàn)呢?
(推薦教程:Python入門教程)
實現(xiàn)代碼:
#導(dǎo)入需要使用到的數(shù)據(jù)模塊
import pandas as pd
import pymysql
#讀入數(shù)據(jù)
filepath = 'E:\_DataSet\catering_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中元素有個類型的強制轉(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() 網(wǎng)頁題目:創(chuàng)新互聯(lián)Python教程:python如何將數(shù)據(jù)插入數(shù)據(jù)庫
轉(zhuǎn)載源于:http://www.dlmjj.cn/article/dpsgcic.html


咨詢
建站咨詢
