mongo_conn = MongoClient( host='127.0.0.1', port=27017, username='uywb', password='sEV+lXxkLa', authSource='ywb_distribution', connect=True ) sqlserver_result = sqlserver_cursor.fetchall() for row in sqlserver_result: i_ui_identifier = row[0] nvc_user_name = row[1] nvc_company = row[2] nvc_phone = row[3] mongo_conn.execute("user_info.insert(i_ui_identifier,nvc_user_name,nvc_company,nvc_phone) VALUES (%s,%s,%s,%s)",(i_ui_identifier,nvc_user_name,nvc_company,nvc_phone))为什么报错说: mongo_conn.execute("user_info.insert(i_ui_identifier,nvc_user_name,nvc_company,nvc_phone) VALUES (%s,%s,%s,%s) ",(i_ui_identifier,nvc_user_name,nvc_company,nvc_phone)) TypeError: 'Database' object is not callable,怎么编写Python代码修改呢
时间: 2024-03-27 14:37:40 浏览: 100
mongo_fdw:已弃用,已移至
MongoClient对象没有execute方法,所以会抛出TypeError异常。正确的语法应该是使用MongoClient的db属性来获取数据库对象,然后使用数据库对象的collection属性来获取集合对象,最后使用集合对象的insert_one方法来插入数据。修改后的代码如下所示:
```python
from pymongo import MongoClient
mongo_conn = MongoClient(
host='127.0.0.1',
port=27017,
username='uywb',
password='sEV+lXxkLa',
authSource='ywb_distribution',
connect=True
)
db = mongo_conn.ywb_distribution # 获取数据库对象
collection = db.user_info # 获取集合对象
sqlserver_result = sqlserver_cursor.fetchall()
for row in sqlserver_result:
i_ui_identifier = row[0]
nvc_user_name = row[1]
nvc_company = row[2]
nvc_phone = row[3]
collection.insert_one({
'i_ui_identifier': i_ui_identifier,
'nvc_user_name': nvc_user_name,
'nvc_company': nvc_company,
'nvc_phone': nvc_phone
}) # 插入数据
```
这样就能正确地将数据插入到MongoDB中了。
阅读全文