#!/usr/bin/perl
use strict;
use warnings;
use DBI;
# Connect to the database, (the directory containing our csv file(s))
my $dbh = DBI->connect("DBI:CSV:f_dir=.;csv_eol=\n;");
# Associate our csv file with the table name 'prospects'
$dbh->{'csv_tables'}->{'prospects'} = { 'file' => 'prospects.csv'};
# Output the name and contact field from each row
my $sth = $dbh->prepare("SELECT * FROM prospects WHERE name LIKE 'G%'");
$sth->execute();
while (my $row = $sth->fetchrow_hashref) {
print("name = ", $row->{'Name'}, " contact = ", $row->{'Contact'}. "\n");
}
$sth->finish();
name = Glenhuntly Pharmacy contact = Paul
name = Gilmour's Shoes contact = Ringo
from sqlalchemy import create_engine, Column, String, Integer, MetaData, Table
from sqlalchemy.orm import mapper, create_session
import csv
CSV_FILE = 'foo.csv'
engine = create_engine('sqlite://') # memory-only database
table = None
metadata = MetaData(bind=engine)
with open(CSV_FILE) as f:
# assume first line is header
cf = csv.DictReader(f, delimiter=',')
for row in cf:
if table is None:
# create the table
table = Table('foo', metadata,
Column('id', Integer, primary_key=True),
*(Column(rowname, String()) for rowname in row.keys()))
table.create()
# insert data into the table
table.insert().values(**row).execute()
class CsvTable(object): pass
mapper(CsvTable, table)
session = create_session(bind=engine, autocommit=False, autoflush=True)
在库中使用DB,比如SQLite。 有Python和Ruby两种版本。
将CSV加载到表中,这里可能也有模块/库可以帮助您。然后走开。
看看Perl和Text::CSV和DBI?在CPAN上有许多模块可以做到这一点。下面是一个例子(来自HERE):
只需在命令提示下键入perldoc DBI和perldoc Text::CSV即可获得更多信息。
有^{} ,包含在python中。使用它,您可以创建一个数据库(在内存中)并向其中添加行,并执行SQL查询。
如果您想要整洁的类似ActiveRecord的功能,您应该添加一个外部ORM,比如sqlalchemy。不过,这是一个单独的下载
使用sqlalchemy的快速示例:
现在您可以查询数据库,按任何字段筛选,等等
假设您在这个csv上运行上面的代码:
它将在内存中创建一个表并填充字段
name
、age
、nickname
。然后可以查询表:它将自动创建并运行一个
SELECT
查询并返回正确的行。使用sqlalchemy的另一个优点是,如果您决定在将来使用另一个功能更强大的数据库,您可以在不更改代码的情况下实际使用它。
相关问题 更多 >
编程相关推荐