我想知道如何使用 sql 读取 csv 文件。我想使用 group by 并将其他 csv 文件连接在一起。我将如何在 python 中解决这个问题。
例子:
select * from csvfile.csv where name LIKE 'name%'
我想知道如何使用 sql 读取 csv 文件。我想使用 group by 并将其他 csv 文件连接在一起。我将如何在 python 中解决这个问题。
例子:
select * from csvfile.csv where name LIKE 'name%'
SQL 代码由数据库引擎执行。Python 不直接理解或执行 SQL 语句。
虽然一些 SQL 数据库将其数据存储在类似 csv 的文件中,但几乎所有数据库都使用更复杂的文件结构。因此,您需要将每个 csv 文件导入 SQL 数据库引擎中的单独表中。然后,您可以使用 Python 连接到 SQL 引擎并向其发送 SQL 语句(例如 SELECT)。该引擎将执行 SQL,从其数据文件中提取结果,并将它们返回给您的 Python 程序。
最常见的轻量级引擎是 SQLite。
littletable是我编写的一个 Python 模块,用于处理对象列表,就好像它们是数据库表一样,但使用的是类似关系的 API,而不是实际的 SQL 选择语句。littletable 中的表格可以轻松地从 CSV 文件中读取和写入。我特别喜欢的功能之一是来自 littletable Table 的每个查询都会返回一个新 Table,因此您不必学习 Table 与 RecordSet 的不同接口。表像列表一样是可迭代的,但它们也可以被选择、索引、连接和旋转 - 请参阅文档的开头页面。
# print a particular customer name
# (unique indexes will return a single item; non-unique
# indexes will return a Table of all matching items)
print customers.by.id["0030"].name
print len(customers.by.zipcode["12345"])
# print all items sold by the pound
for item in catalog.query(unitofmeas="LB"):
print item.sku, item.descr
# print all items that cost more than 10
for item in catalog.where(lambda o : o.unitprice>10):
print item.sku, item.descr, item.unitprice
# join tables to create queryable wishlists collection
wishlists = customers.join_on("id") + wishitems.join_on("custid") + catalog.join_on("sku")
# print all wishlist items with price > 10
bigticketitems = wishlists().where(lambda ob : ob.unitprice > 10)
for item in bigticketitems:
print item
表的列是从添加到表中的对象的属性推断出来的。namedtuples 也很好,还有一种特殊的、大部分不可变的类型,称为 DataObject,也在 littletable 中定义。
littletable 需要一点时间来适应,但听起来你已经在考虑类似的问题了。
您可以使用 PHP 脚本轻松查询 SQL 数据库。PHP 运行服务器端,因此您的所有代码都必须位于网络服务器(带有数据库的服务器)上。您可以像这样创建一个连接到数据库的函数:
$con= mysql_connect($hostname, $username, $password)
or die("An error has occured");
然后使用$con
来完成其他任务,例如循环数据和创建表,甚至向现有表添加行和列。
编辑:我注意到你说 .CSV 文件。您可以将 CSV 文件上传到 SQL 数据库并从中创建一个表。如果您使用的是 phpMyAdmin 等控制面板服务,您只需将 CSV 文件导入数据库,如下所示:
如果您正在寻找免费的网络主机来测试您的 SQL 和 PHP 文件,请查看x10托管。