使用Pymongo将字符串输入到MongoDB中

时间:2015-06-11 04:18:34

标签: mongodb python-2.7 pymongo

我试图让用户输入数据来执行插入,只要我有数字就可以工作,但是当我输入字母时它会给我错误“LettersUsed”没有定义。我尝试将输入转换为str(输入('Whatever'))但是没有做任何帮助为什么这样做呢?

import pymongo
import sys

#get a connection to database
connection = pymongo.MongoClient('mongodb://localhost')
    #get a handle to database
db=connection.test
vehicles=db.vehicles

vehicle_VIN = input('What is the Vehicle VIN number? ')
vehicle_Make = input('What is the Vehicle Make? ')
newVehicle = {'VIN' : (vehicle_VIN).upper(), 'Make' : (vehicle_Make)}

try:
    vehicles.insert_one(newVehicle)
    print ('New Vehicle Inserted')

except  Exception as e:
        print 'Unexpected error:', type(e), e

#print Results
results = vehicles.find()

print()
# display documents in collection
for record in results:
    print(record['VIN'] + ',',record['Make'])
#close the connection to MongoDB
connection.close()

1 个答案:

答案 0 :(得分:0)

  

消息:名称'DAFEQF'未定义

在Python 2中,代码input()等于eval(raw_input(prompt))。这意味着无论您输入什么输入,Python2都会尝试“评估”该输入,并会抱怨您的输入未定义。

确保将input()替换为raw_input()(这仅适用于Python2!)

替换

vehicle_VIN = input('What is the Vehicle VIN number? ')
vehicle_Make = input('What is the Vehicle Make? ')

vehicle_VIN = raw_input('What is the Vehicle VIN number? ')
vehicle_Make = raw_input('What is the Vehicle Make? ')