python 使用sqlalchemy将csv文件加载到数据库

2lpgd968  于 2023-02-07  发布在  Python
关注(0)|答案(6)|浏览(275)

我想将csv文件加载到数据库中

smdncfj3

smdncfj31#

由于SQLAlchemy的强大功能,我也在一个项目中使用它。它的强大功能来自于面向对象的方式与数据库“对话”,而不是硬编码SQL语句,后者可能是一个痛苦的管理。更不用说,它还快得多。
坦率地说,是的!使用SQLAlchemy将CSV中的数据存储到数据库中是小菜一碟。下面是一个完整的工作示例(我使用了SQLAlchemy 1.0.6和Python 2.7.6):

from numpy import genfromtxt
from time import time
from datetime import datetime
from sqlalchemy import Column, Integer, Float, Date
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

def Load_Data(file_name):
    data = genfromtxt(file_name, delimiter=',', skip_header=1, converters={0: lambda s: str(s)})
    return data.tolist()

Base = declarative_base()

class Price_History(Base):
    #Tell SQLAlchemy what the table name is and if there's any table-specific arguments it should know about
    __tablename__ = 'Price_History'
    __table_args__ = {'sqlite_autoincrement': True}
    #tell SQLAlchemy the name of column and its attributes:
    id = Column(Integer, primary_key=True, nullable=False) 
    date = Column(Date)
    opn = Column(Float)
    hi = Column(Float)
    lo = Column(Float)
    close = Column(Float)
    vol = Column(Float)

if __name__ == "__main__":
    t = time()

    #Create the database
    engine = create_engine('sqlite:///csv_test.db')
    Base.metadata.create_all(engine)

    #Create the session
    session = sessionmaker()
    session.configure(bind=engine)
    s = session()

    try:
        file_name = "t.csv" #sample CSV file used:  http://www.google.com/finance/historical?q=NYSE%3AT&ei=W4ikVam8LYWjmAGjhoHACw&output=csv
        data = Load_Data(file_name) 

        for i in data:
            record = Price_History(**{
                'date' : datetime.strptime(i[0], '%d-%b-%y').date(),
                'opn' : i[1],
                'hi' : i[2],
                'lo' : i[3],
                'close' : i[4],
                'vol' : i[5]
            })
            s.add(record) #Add all the records

        s.commit() #Attempt to commit all the records
    except:
        s.rollback() #Rollback the changes on error
    finally:
        s.close() #Close the connection
    print "Time elapsed: " + str(time() - t) + " s." #0.091s

(Note:这不一定是做到这一点的“最佳”方式,但我认为这种格式对于初学者来说可读性很强;它速度也非常快:插入251条记录时为0.091s!)
我想如果您一行一行地浏览它,您会发现使用它是多么容易。注意缺少SQL语句--太好了!我还冒昧地使用numpy在两行中加载CSV内容,但是如果您愿意,也可以不使用它。
如果你想和传统的方法进行比较,这里有一个完整的例子可以参考:

import sqlite3
import time
from numpy import genfromtxt

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

def Create_DB(db):      
    #Create DB and format it as needed
    with sqlite3.connect(db) as conn:
        conn.row_factory = dict_factory
        conn.text_factory = str

        cursor = conn.cursor()

        cursor.execute("CREATE TABLE [Price_History] ([id] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, [date] DATE, [opn] FLOAT, [hi] FLOAT, [lo] FLOAT, [close] FLOAT, [vol] INTEGER);")

def Add_Record(db, data):
    #Insert record into table
    with sqlite3.connect(db) as conn:
        conn.row_factory = dict_factory
        conn.text_factory = str

        cursor = conn.cursor()

        cursor.execute("INSERT INTO Price_History({cols}) VALUES({vals});".format(cols = str(data.keys()).strip('[]'), 
                    vals=str([data[i] for i in data]).strip('[]')
                    ))

def Load_Data(file_name):
    data = genfromtxt(file_name, delimiter=',', skiprows=1, converters={0: lambda s: str(s)})
    return data.tolist()

if __name__ == "__main__":
    t = time.time() 

    db = 'csv_test_sql.db' #Database filename 
    file_name = "t.csv" #sample CSV file used:  http://www.google.com/finance/historical?q=NYSE%3AT&ei=W4ikVam8LYWjmAGjhoHACw&output=csv

    data = Load_Data(file_name) #Get data from CSV

    Create_DB(db) #Create DB

    #For every record, format and insert to table
    for i in data:
        record = {
                'date' : i[0],
                'opn' : i[1],
                'hi' : i[2],
                'lo' : i[3],
                'close' : i[4],
                'vol' : i[5]
            }
        Add_Record(db, record)

    print "Time elapsed: " + str(time.time() - t) + " s." #3.604s

(Note:即使采用“旧”方法,这也决不是最好的方法,但它可读性很强,是SQLAlchemy方法与“旧”方法的“1对1”转换。)
请注意SQL语句:一个用于创建表,另一个用于插入记录。另外,注意维护长SQL字符串比简单的类属性添加要麻烦一些。到目前为止喜欢SQLAlchemy吗?
当然,对于外键查询,SQLAlchemy也有能力做到这一点。下面是一个例子,说明了class属性在外键赋值时的样子(假设ForeignKey类也是从sqlalchemy模块导入的):

class Asset_Analysis(Base):
    #Tell SQLAlchemy what the table name is and if there's any table-specific arguments it should know about
    __tablename__ = 'Asset_Analysis'
    __table_args__ = {'sqlite_autoincrement': True}
    #tell SQLAlchemy the name of column and its attributes:
    id = Column(Integer, primary_key=True, nullable=False) 
    fid = Column(Integer, ForeignKey('Price_History.id'))

它将“fid”列作为外键指向Price_History的id列。
希望能有所帮助!

wlsrxk51

wlsrxk512#

如果你的CSV文件很大,使用INSERT是非常无效的。你应该使用批量加载机制,这在不同的基中是不同的。例如,在PostgreSQL中你应该使用“COPY FROM”方法:

with open(csv_file_path, 'r') as f:    
    conn = create_engine('postgresql+psycopg2://...').raw_connection()
    cursor = conn.cursor()
    cmd = 'COPY tbl_name(col1, col2, col3) FROM STDIN WITH (FORMAT CSV, HEADER FALSE)'
    cursor.copy_expert(cmd, f)
    conn.commit()
nukf8bse

nukf8bse3#

我也遇到过同样的问题,我发现对Pandas采用两步疗法反而更容易:

import pandas as pd
with open(csv_file_path, 'r') as file:
    data_df = pd.read_csv(file)
data_df.to_sql('tbl_name', con=engine, index=True, index_label='id', if_exists='replace')

请注意,我的方法与this one类似,但不知何故Google将我发送到了这个线程,所以我想我将分享。

tjvv9vkg

tjvv9vkg4#

要使用sqlalchemy将一个相对较小的CSV文件导入数据库,可以使用engine.execute(my_table.insert(), list_of_row_dicts),如sqlalchemy教程的“执行多条语句”一节中详细描述的那样。
这有时称为“executemany”调用样式,因为它会导致executemany DBAPI调用。DB驱动程序可能会执行单个多值INSERT .. VALUES (..), (..), (..)语句,从而减少到DB的往返次数并加快执行速度:

根据sqlalchemy的FAQ,这是在不使用特定于DB的批量加载方法(如Postgres中的COPY FROM、MySQL中的LOAD DATA LOCAL INFILE等)的情况下可以获得的最快速度。特别是,它比使用普通ORM(如@Manuel J.迪亚兹在这里的回答)、bulk_save_objectsbulk_insert_mappings更快。

import csv
from sqlalchemy import create_engine, Table, Column, Integer, MetaData

engine = create_engine('sqlite:///sqlalchemy.db', echo=True)

metadata = MetaData()
# Define the table with sqlalchemy:
my_table = Table('MyTable', metadata,
    Column('foo', Integer),
    Column('bar', Integer),
)
metadata.create_all(engine)
insert_query = my_table.insert()

# Or read the definition from the DB:
# metadata.reflect(engine, only=['MyTable'])
# my_table = Table('MyTable', metadata, autoload=True, autoload_with=engine)
# insert_query = my_table.insert()

# Or hardcode the SQL query:
# insert_query = "INSERT INTO MyTable (foo, bar) VALUES (:foo, :bar)"

with open('test.csv', 'r', encoding="utf-8") as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=',')
    engine.execute(
        insert_query,
        [{"foo": row[0], "bar": row[1]} 
            for row in csv_reader]
    )
yx2lnoni

yx2lnoni5#

带有逗号和标题名称的CSV文件到PostrgeSQL
1.我使用的是csv Python阅读器。CSV数据用逗号(,)分隔
1.然后将其转换为Pandas数据框。列的名称与您的csv文件中相同。
1.结束最后一个数据框到sql,引擎作为到DB的连接。if_exists ='replace/append'

import csv
import pandas as pd
from sqlalchemy import create_engine

# Create engine to connect with DB
try:
    engine = create_engine(
        'postgresql://username:password@localhost:5432/name_of_base')
except:
    print("Can't create 'engine")

# Get data from CSV file to DataFrame(Pandas)
with open('test.csv', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    columns = ['one', 'two', 'three']
    df = pd.DataFrame(data=reader, columns=columns)

# Standart method of Pandas to deliver data from DataFrame to PastgresQL
try:
    with engine.begin() as connection:
        df.to_sql('name_of_table', con=connection, index_label='id', if_exists='replace')
        print('Done, ok!')
except:
    print('Something went wrong!')
rbl8hiat

rbl8hiat6#

这是我能让它工作的唯一方法,其他的答案都没有显式地提交游标的连接,这也意味着你在使用现代的python,sqlalchemy,显然还有postgres,因为语法使用COPY ... FROM
它没有错误处理,可能不安全,并且使用ORMMap器定义中所有不是主键的列,但是对于简单的任务,它可能会做得很好。

import pathlib

import sqlalchemy

Base: sqlalchemy.orm.DeclarativeMeta = db.orm.declarative_base()

def upload_to_model_table(
        Model: Base,
        csv_file_path: pathlib.Path,
        engine: sqlalchemy.engine,
        header=True,
        delimiter=';'
):
    """ It's assumed you're using postgres, otherwise this won't work. """
    fieldnames = ', '.join([
        f'"{col.name}"' for col in Model.__mapper__.columns if not col.primary_key
    ])

    sql = """
    COPY {0} ({1}) FROM stdin WITH (format CSV, header {2}, delimiter '{3}')
    """.format(Model.__tablename__, fieldnames, header, delimiter)

    with engine.connect() as connection:
        cursor = connection.connection.cursor()
        with open(csv_file_path, 'rt', encoding='utf-8') as csv_file:
            cursor.copy_expert(sql, csv_file)
        cursor.connection.commit()
        cursor.close()

相关问题