2012-12-10 31 views
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 

请帮助....日Thnx提前..

+3

向我们展示您的'servinfo.txt' – NPE

回答

1

您至少有一个rowtypesFile不具有在它,逗号:

>>> '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) 

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

+0

现在,当我尝试此代码..我得到了一个错误。追踪(最近呼叫最后): 文件“C:\ Python27 \ programs new \ codes.py” ,第8行,在 dataTypes = dict(csvreader) ValueError:字典更新序列元素#0的长度为1; 2是必需的。我是新的python .. PLZ是特定的.. thnx -Martijn Pieters – priya

+0

@priya:这是没有逗号的行。你需要检查你的'servinfo.txt'文件,并确保*每行都有* 2 *列。 –