我尝试连接和读取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%确定,即使有文档,我也不知道如何解决这个问题。
谢谢。
答案 0 :(得分:0)
我正在读你的代码。我在程序开头看到,您创建dbco
变量以指向空字符串:
dbco = ''
之后,我看到您定义了几个函数,然后在该字符串上调用find()
:
user_info = dbco.find({})
您将{}
(空dict)作为参数传递给方法...但正如您在文档here中所看到的,此方法需要另一个字符串作为第一个参数。这会导致您看到的错误。
现在我不完全确定如何修复它,因为我不知道你的意思。也许你的意思是使用dataconnect
变量,因为那是获得connectToMongoDb
函数结果的变量:
dataconnect = connectToMongoDb()
答案 1 :(得分:0)
我再次成功并改变了一些小事。现在,它的工作原理。以下是代码,适用于将来需要它的人。
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()