【问题标题】:Writing generic script to upload data from file into database table编写通用脚本将数据从文件上传到数据库表
【发布时间】:2012-11-23 07:11:36
【问题描述】:

请考虑这种情况:

我在数据库中有不同的表,比如 table1,table2,table3.....

现在,对于这些表中的每一个,我都有数据进入平面文件,这些文件将被插入到相应的表中。

我想编写一个通用脚本,它将读取平面文件的第一行,并通过将平面文件中的数据类型与存在的表的架构相匹配来确定应该将其插入到哪个表中。

假设:考虑的所有表都将具有不同的架构。

请建议这是否可行,如果可行,请指导如何实现。

【问题讨论】:

  • 这是可行的,但非常棘手。您需要对脚本可用的每个表进行适当的描述。您需要一个适度复杂的工具来对输入字段进行分类(123 看起来非常像 '123' - 字符串 vs 整数 vs 小数 vs ...)。而且你只会在一般情况下启发式地正确。

标签: python c database shell


【解决方案1】:

你可以试试这个通用代码:

import os
import glob
import MySQLdb

path = '/path/to/directory/containing/flatfiles'
conn_mysql = MySQLdb.connect(host = "localhost",user = "root",passwd="root",db="dbname")
cursor_mysql = conn_mysql.cursor()
table_to_use = ""
for filename in glob.glob( os.path.join(path, '*.txt') ):
    print "Reading file: " + filename
    currentfile = open(filename, 'r')
    numcols = currentfile[0].split()
    if numcols is 10:
        table_to_use = "tbl1"
    elif numcols is 7:
        table_to_use = "tbl2"
    # So on and so forth
    for line in currentfile[1:]:
        insert_data_to_database(line, table_to_use)
        #use the above function to insert data based on the table_to_use

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多