从CSV信息创建SQL表

时间:2018-09-07 07:01:11

标签: python sql sql-server python-2.7

我试图用Python 2编写一段代码,该代码将读取CSV并相应地创建SQL表,但是在尝试执行SQL查询时出现错误。 (我省略了与SQL的连接,因为其中包含密码等)

有人可以看到我要去哪里了吗?

错误-

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server 
Driver][SQL Server]Incorrect syntax near '1099'. (102) (SQLExecDirectW)")





m = re.search('.*\((.*)\)', _filename)

tablename = m.group(1)

extra_columns = [
    ]
valid_column_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

for filename in os.listdir('.'):
    filename_no_ext, ext = os.path.splitext(filename)
    if ext.lower() == '.csv':
        csv_filename = filename
        break

with open(csv_filename, 'rb') as fin:
    reader = csv.reader(fin)

    headers = reader.next()

    for column in extra_columns:
        headers.append(column)

    nice_columns = []
    for column in headers:
        column = column.replace(' ', '')

        nice_column = ''
        for c in column:
            if c in valid_column_letters:
                nice_column += c

        nice_columns.append(nice_column)

    print 'Created table %s' % (tablename,)
    for column in nice_columns:
        print column

    command = 'CREATE TABLE ? (?);', '? VARCHAR(1000)'(tablename, for c in nice_columns)

    #command = 'CREATE TABLE %s (%s);' % (tablename, ','.join('%s VARCHAR(1000)' % (c,) for c in nice_columns))

    cursor.execute(command)

    cursor.commit()

感谢您提供任何反馈意见,因此我可以解决此问题。 TY

0 个答案:

没有答案