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
请帮助....提前thnx ..
最佳答案
您在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)
那不会解决您的问题,尽管该文件中有一行没有逗号,但是您必须首先解决该问题。