如何将txt文件中的数据写入数据库?
如果我有一个具有一定行数和列数的txt(一开始未知列数,列之间用制表符分隔),如何将数据导出到数据库中?我已经设法迭代第一行来计算列数并相应地创建一个表,但现在我需要遍历每一行并将数据插入到相应的列中。我怎样才能做到这一点?
txt 文件示例:
Name Size Population GDP
aa 2344 1234 12
bb 2121 3232 15
... ... .. ..
.. .. .. ..
表已创建:
CREATE TABLE random id INT, Name char(20), Size INT, Population INT, GDP INT
If I have a txt with a certain number of rows and column (number of columns unknown at the beginning, columns are separated by tab), how can I export the data into the database? I have managed to iterate through the first row to count the number of columns and create a table accordingly but now I need to go through each row and insert the data into the respective column. How can I do that?
Example of the txt file:
Name Size Population GDP
aa 2344 1234 12
bb 2121 3232 15
... ... .. ..
.. .. .. ..
The table has been created:
CREATE TABLE random id INT, Name char(20), Size INT, Population INT, GDP INT
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
困难的部分是在文本字段中阅读。根据您的定义,字段标题由空格分隔。对于文本字段来说是这样吗?
通用过程是:
另一种解决方案是将 TXT 文件转换为制表符或逗号分隔字段。检查您的数据库文档,看看是否有加载文件的功能,并发现用于分隔列的字符。
如果您需要具体帮助,请提出更具体或更详细的问题。
The difficult part is reading in the text fields. According to your definition, the field titles are separated by spaces. Is this true for the text fields?
A generic process is:
Another solution is to convert the TXT file into tab or comma separated fields. Check your database documentation to see if there is a function for loading files and also discover the characters used for separating columns.
If you need specific help, please ask a more specific or detailed question.
使用 PostgreSQL 的 COPY 命令,如下所示:
Using PostgreSQL's COPY, command, something like:
像这样的东西可能会起作用。
基本思想是使用打印语句将行转换为 SQL 命令。
然后您可以使用 sql 命令解释器执行这些命令。
对于未知数量的列,这可能有效。
将 ID 替换为所需的 id 值。但您需要为每个 ID 值单独执行它。
something like this might work.
basic idea is to use print statements to transform the line into SQL commannds.
then you can execute these commands using a sql command interpreter.
for the unknown number of columns, this might work.
replace ID with the id value needed. but you will need to execute it separately for each ID value.
我使用 Sybase,其中“bcp”实用程序执行此操作。快速谷歌“postgres bcp”带来了这个:
http://lists.plug.phoenix.az.us/pipermail/plug-devel/2000-October/000103.html
我意识到这不是最好的答案,但我希望足以让你继续前进。
哦,您可能需要更改文本格式,使其以逗号或制表符分隔。为此使用 sed。
I work with Sybase where "bcp" utility does this. Quick google on "postgres bcp" brings up this:
http://lists.plug.phoenix.az.us/pipermail/plug-devel/2000-October/000103.html
I realize its not the best answer, but good enough to get you going, I hope.
Oh, and you may need to change your text format, make it comma or tab-delimited. Use sed for that.