[英]Pymongo, TypeError : expected a character buffer object
我正在嘗試連接並讀取MongoDB數據庫中的數據,以學習Python。 我正在使用Pymongo,但出現此錯誤:
Traceback (most recent call last):
File "secondtest.py", line 107, in <module>
user_info = dbco.find({})
TypeError: expected a character buffer object
這是我的database.ini:
[postgresql]
host=monhostname
database=monpass
port=15000
user=monuser
password=monpass
[mongodb]
hostname=127.0.0.1
database=Mydatabase
username=Myname
password=Myn@me!
collection=measure
port=27017
和我的代碼使用它:
# -*- coding: utf-8 -*-
# secondtest.py
import psycopg2
import sys
import pymongo
from urllib import quote_plus
from pymongo import MongoClient
from configparser import ConfigParser
# Connection information in database.ini
params = ''
mongollection = ''
# Variables to connect to a database, to use a cursor object and to fetch all results from a query
mongoClient = ''
pgsqlClient = ''
pgsqlCursor = ''
pgsqlRecords = ''
mongoRecords = ''
dbco = ''
# Retrieve connection information from ini file
def dbConfig(section, filename='database.ini'):
# Create a parser
parser = ConfigParser()
# Read config file
parser.read(filename)
# Get section, depending on the database engine
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
# Return data or directly as a string
if section == 'postgresql':
return db
elif section == 'mongodb':
host = ''
username = ''
passwd = ''
port = ''
dbmongo = ''
connectstring = ''
# Make a string to connect to MongoDB
for key, value in db.iteritems():
if key == 'hostname':
host = value.encode("utf-8")
elif key == 'username':
username = value
elif key == 'password':
passwd = value
elif key == 'database':
dbmongo = value
elif key == 'collection':
mongollection = value
elif key == 'port':
port = value
connectstring = "mongodb://" + username + ":" + quote_plus(passwd) + "@" + host + ":" + port
print("Internal test = " + connectstring)
return connectstring.encode('iso-8859-1')
# Connection to MongoDB
def connectToMongoDb():
# The f-string is only available in Python >= 3.6
params = dbConfig('mongodb')
print("Parameters : " + params)
mongoClient = MongoClient(params)
try:
# print("Connection to database")
dbco = mongoClient.mongollection
print("Here")
print("Test dbco : " + dbco)
print("Connected to MongoDB !")
return dbco
except:
return "Error : can't connect to MongoDB !"
# Close MongoDB connection
def closeMongoDbConnection():
# try:
mongoClient.close()
return 'Connection closed'
# except:
# return "Can't close the connection. See if you already had one or if you didn't mispell its name."
# Make a query in MongoDB
def mongoDbQuery():
#mongocursor = mongoClient.mongollection.find()
#for document in cursor:
#print(document)
mongoClient.database_names()
if __name__ == '__main__':
dataconnect = connectToMongoDb()
print("Connection\n")
#mongoDbQuery()
#collec = mongoClient.measure
user_info = dbco.find({})
print(user_info)
print(closeMongoDbConnection())
您能幫我解決這個問題嗎? 我認為quote_plus()甚至dbco = mongoClient.mongollection是導致此錯誤發生的原因。 但是我不確定100%,即使有文檔,我也看不到如何解決此問題。
謝謝。
我正在閱讀您的代碼。 我在程序的開頭看到,您創建了dbco
變量以指向一個空字符串:
dbco = ''
之后,我看到您定義了幾個函數,然后在該字符串上調用find()
:
user_info = dbco.find({})
您正在將{}
(空dict)作為參數傳遞給方法...但是如您在此處的文檔中所見,此方法需要另一個字符串作為第一個參數。 這會導致您看到錯誤。
現在,我不完全確定如何解決它,因為我不知道您的意思。 也許您的意思是使用dataconnect
變量,因為那是獲取connectToMongoDb
函數結果的變量:
dataconnect = connectToMongoDb()
我又做了一次,改變了一些小東西。 現在,它可以工作了。 這是代碼,供將來需要的人使用。
import sys
import pymongo
from urllib import quote_plus
from pymongo import MongoClient
from configparser import ConfigParser
client = MongoClient()
connected = ''
# Retrieve connection information from ini file
def dbConfig(section, filename='database.ini'):
# Keep result in global variable when the function is finished
global client
# Create a parser
parser = ConfigParser()
# Read config file
parser.read(filename)
# Get section, depending on the database engine
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
# Return data or directly as a string
if section == 'postgresql':
return db
elif section == 'mongodb':
# Variables for the connection
host = ''
username = ''
passwd = ''
port = ''
connectstring = ''
# Make a string to connect to MongoDB
for key, value in db.iteritems():
if key == 'hostname':
host = value.encode("utf-8")
elif key == 'username':
username = value
elif key == 'password':
passwd = value
elif key == 'database':
dbmongo = value
elif key == 'collection':
mongollection = value
elif key == 'port':
port = value
# Make the URI needed for the connection to Mongo DB
passwing = "mongodb://" + username + ":" + quote_plus(passwd) + "@" + host + ":" + port
client = MongoClient(passwing)
return client
# Close MongoDB connection
def closeMongoDbConnection():
# Try to close the connection to Mongo DB
try:
client.close()
return 'Connection closed'
except:
return "Can't close the connection. See if you already had one or if you didn't mispell its name."
# Connection to MongoDB
def connectToMongoDb(mydb):
db = client.get_database(mydb)
return db.measure
# Make a query in MongoDB
def mongoDbQuery():
docs = connected.find().count()
#for document in docs:
#print(document)
print(docs)
if __name__ == '__main__':
connected = connectToMongoDb('neocampus')
#docs = connected.find()
# print(test)
#for document in docs:
#print(document)
mongoDbQuery()
# Show if the connection to Mongo DB is a success or not
print(closeMongoDbConnection())
問題是:-關於函數中的全局變量和函數外的信息-數據庫變量為空(因此)-首次調用MongoClient()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.