[英]How to write database content in a csv file and download it using Python
[英]How to write csv file into sql database with python
我有csv文件,其中包含有關計算機的某些信息,例如ostype,ram,cpu值,並且ı具有已經具有相同信息的sql數據庫,並且ı要通過python腳本更新該數據庫表。 數據庫表和csv文件具有唯一的“ id”參數。
import csv
with open("Hypersanal.csv") as csvfile:
readCSV = csv.reader(csvfile, delimiter=';')
for row in readCSV:
print row
根據數據庫的類型,將對代碼進行一些細微調整。
對於此示例,我將結合使用SQLAlchemy和pymysql驅動程序。 要找出連接字符串的第一部分應該是什么(取決於您要連接的數據庫的類型),請檢查有關方言的SQLAlchemy Doc 。
首先,我們導入必要的模塊
from sqlalchemy import *
from sqlalchemy.orm import create_session
from sqlalchemy.ext.declarative import declarative_base
然后,我們創建連接字符串
dialect_part = "mysql+pymysql://"
# username is the usernmae we'll use to connect to the db, and password the corresponding password
# server_name is the name fo the server where the db is. It INCLUDES the port number (eg : 'localhost:9080')
# database is the name of the db on the server we'll work on
connection_string = dialect_part+username+":"+password+"@"+server_name+"/"+database
SQLAlchemy需要其他一些設置:
Base = declarative_base()
engine = create_engine(connection_string)
metadata = MetaData(bind=engine)
現在,我們有一個到數據庫的鏈接,但是需要更多的工作才能對其執行任何操作。
我們創建一個與將要命中的數據庫表相對應的類。 此類將根據表在數據庫中的方式“自動填充”。 您也可以手動填寫。
class TableWellHit(Base):
__table__ = Table(name_of_the_table, metadata, autoload=True)
現在,為了能夠與表進行交互,我們需要創建一個會話:
session = create_session(bind=engine)
現在,我們需要開始會議,然后進行設置。 現在將使用您的代碼。
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])
例如,假設您在表中需要字段“ username”和“ password”,並且行包含字典,字典中包含“ user”和“ pass”作為鍵。
元素將通過以下方式創建: TableWellHit(username=row['user],password=row['pass'])
# 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()
希望這能回答您的問題,如果他沒有回答,請告訴我,以便我糾正我的回答。
編輯:
對於MSSQL:
-安裝pymssql ( pip install pymssql
)
根據此SQLAlchemy頁面 , connection_string
應采用以下形式: mssql+pymssql://<username>:<password>@<freetds_name>/?charset=utf8
使用合並允許您根據值是否已存在來創建或更新值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.