使用脚本语言的动态数据库

2024-06-06 21:11:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组.csv文件要处理。用SQL查询处理它要容易得多。我想知道是否有办法加载一个.csv文件,并使用SQL语言和python或ruby这样的脚本语言来查看它。用类似于ActiveRecord的东西加载它会非常棒。

问题是我不想在运行脚本之前运行数据库。我不需要脚本语言和一些模块之外的附加安装。

我的问题是我应该使用哪种语言和什么模块来完成这项任务。我环顾四周,找不到任何适合我需要的东西。有可能吗?


Tags: 模块文件csv脚本语言数据库sql脚本语言
3条回答

在库中使用DB,比如SQLite。 有PythonRuby两种版本。

将CSV加载到表中,这里可能也有模块/库可以帮助您。然后走开。

看看Perl和Text::CSV和DBI?在CPAN上有许多模块可以做到这一点。下面是一个例子(来自HERE):

#!/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

只需在命令提示下键入perldoc DBI和perldoc Text::CSV即可获得更多信息。

^{},包含在python中。使用它,您可以创建一个数据库(在内存中)并向其中添加行,并执行SQL查询。

如果您想要整洁的类似ActiveRecord的功能,您应该添加一个外部ORM,比如sqlalchemy。不过,这是一个单独的下载

使用sqlalchemy的快速示例:

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)

现在您可以查询数据库,按任何字段筛选,等等

假设您在这个csv上运行上面的代码:

name,age,nickname
nosklo,32,nosklo
Afila Tun,32,afilatun
Foo Bar,33,baz

它将在内存中创建一个表并填充字段nameagenickname。然后可以查询表:

for r in session.query(CsvTable).filter(CsvTable.age == '32'):
    print r.name, r.age, r.nickname

它将自动创建并运行一个SELECT查询并返回正确的行。

使用sqlalchemy的另一个优点是,如果您决定在将来使用另一个功能更强大的数据库,您可以在不更改代码的情况下实际使用它。

相关问题 更多 >