python处理csv文件 sql_如何用python将csv文件写入sql数据库
根據(jù)數(shù)據(jù)庫(kù)的類(lèi)型,代碼會(huì)有一些細(xì)微的調(diào)整。
對(duì)于本例,我將使用SQLAlchemy和pymysql驅(qū)動(dòng)程序。要確定連接字符串的第一部分應(yīng)該是什么(取決于要連接到的數(shù)據(jù)庫(kù)的類(lèi)型),請(qǐng)選中SQLAlchemy Doc about Dialects。在
首先,我們導(dǎo)入必要的模塊from sqlalchemy import *
from sqlalchemy.orm import create_session
from sqlalchemy.ext.declarative import declarative_base
然后,我們創(chuàng)建連接字符串
^{pr2}$
SQLAlchemy還需要一些設(shè)置:Base = declarative_base()
engine = create_engine(connection_string)
metadata = MetaData(bind=engine)
現(xiàn)在,我們有了一個(gè)到數(shù)據(jù)庫(kù)的鏈接,但在對(duì)其進(jìn)行任何操作之前,還需要一些工作。
我們創(chuàng)建了一個(gè)與要命中的數(shù)據(jù)庫(kù)表相對(duì)應(yīng)的類(lèi)。這個(gè)類(lèi)將根據(jù)表在數(shù)據(jù)庫(kù)中的位置“自動(dòng)填充”。也可以手動(dòng)填充。在class TableWellHit(Base):
__table__ = Table(name_of_the_table, metadata, autoload=True)
現(xiàn)在,為了能夠與表交互,我們需要?jiǎng)?chuàng)建一個(gè)會(huì)話:session = create_session(bind=engine)
現(xiàn)在,我們需要開(kāi)始會(huì)話,然后我們就可以開(kāi)始了。
現(xiàn)在將使用您的代碼。在import csv
with open("Hypersanal.csv") as csvfile:
readCSV = csv.reader(csvfile, delimiter=';')
for row in readCSV:
# print row
# I chose to push each value from the db one by one
# If you're sure there won't be any duplicates for the primary key, you can put the session.begin() before the for loop
session.begin()
# I create an element for the db
new_element = TableWellHit(field_in_table=row[field])
例如,假設(shè)您在表中需要字段“username”和“password”,而行包含一個(gè)包含“user”和“pass”作為鍵的措辭。
元素將由:TableWellHit(username=row['user],password=row['pass'])創(chuàng)建# I add the element to the table
# I choose to merge instead of add, so as to prevent duplicates, one more time
session.merge(new_element)
# Now, we commit our changes to the db
# This also closes the session
# if you put the session.begin() outside of the loop, do the same for the session.commit()
session.commit()
希望這能回答你的問(wèn)題,如果他沒(méi)有,請(qǐng)告訴我,這樣我就可以更正我的答案。在
編輯:
對(duì)于MSSQL:
-安裝pymssql(pip install pymssql)
根據(jù)這個(gè)connection_string應(yīng)該是下面的形式SQLAlchemy page:mssql+pymssql://:@/?charset=utf8
使用merge可以創(chuàng)建或更新值,具體取決于它是否已經(jīng)存在。在
總結(jié)
以上是生活随笔為你收集整理的python处理csv文件 sql_如何用python将csv文件写入sql数据库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python.exe在哪个文件_pyth
- 下一篇: 用python实现链表_用Python实