0
import MySQLdb
import pyodbc


typesFile = open('servinfo.txt', 'r').readlines()
dataTypes = dict((row.split(',')[0].strip(),row.split(',')[1].strip()) for row in typesFile)   


conn = pyodbc.connect('DRIVER={FreeTDS}; SERVER=prsoft; DATABASE=blueseas; UID=sa;    PWD=tiger')
msCursor = conn.cursor()


db = MySQLdb.connect(passwd="pr", db="tenable")
myCursor = db.cursor()

msCursor.execute("SELECT * FROM airlinemaster WHERE type='U'") 
dbTables = msCursor.fetchall()
noLength = [56, 58, 61] 

for tbl in dbTables:
msCursor.execute("SELECT * FROM airlinemaster WHERE airline = air india('%s')" % tbl[0]) #syscolumns: see sysobjects above.
columns = msCursor.fetchall()
attr = ""
for col in columns:
colType = dataTypes[str(col.xtype)] 


if col.xtype == 60:
    colType = "float"
    attr += col.name +" "+ colType + "(" + str(col.length) + "),"
elif col.xtype in noLength:
    attr += col.name +" "+ colType + ","
else:
    attr += col.name +" "+ colType + "(" + str(col.length) + "),"

attr = attr[:-1]
myCursor.execute("CREATE TABLE " + tbl[0] + " (" + attr + ");") #create the new table and all columns
msCursor.execute("select * from %s" % tbl[0])
tblData = msCursor.fetchall()

#populate the new MySQL table with the data from MSSQL
for row in tblData:
fieldList = ""
for field in row:
    if field == None: 
    fieldList += "NULL,"
    else:
    field = MySQLdb.escape_string(str(field))
    fieldList += "'"+ field + "',"

fieldList = fieldList[:-1]
myCursor.execute("INSERT INTO " + tbl[0] + " VALUES (" + fieldList + ")" )

我已经以多种方式尝试了上面的代码来导入数据..但由于列表索引超出范围仍然不断出错..不知道我哪里出错了..我该如何解决这个问题?

 Traceback (most recent call last):
 File "C:\Python27\programs new\codes.py", line 10, in <module>
 dataTypes = dict((row.split(',')[0].strip(),row.split(',')[1].strip()) for row in typesFile)
 File "C:\Python27\programs new\codes.py", line 10, in <genexpr>
 dataTypes = dict((row.split(',')[0].strip(),row.split(',')[1].strip()) for row in typesFile)
 IndexError: list index out of range

请帮助..提前谢谢..

4

1 回答 1

1

您至少有一个其中row没有typesFile逗号,

>>> 'line without a comma'.split(',')
['line without a comma']
>>> 'line without a comma'.split(',')[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

如果servinfo.txt应该是包含两列的逗号分隔文件,为什么不使用csv模块来读取它呢?

import csv
csvreader = csv.reader(open('servinfo.txt', 'rb'))
dataTypes = dict(csvreader)

但是,这并不能解决您的问题,因为该文件中有一行没有逗号,您必须先解决该问题。

于 2012-12-10T09:09:28.430 回答