使用Python 2.7 CURD 操作非关系型数据库MongoDB
2011-11-30 17:25
1171 查看
在进行数据库的操作过程中,有些数据的格式没有关系,也即它是非关系型的时候,我们会用到非关系型数据库,
而MongoDB是一个由C++写的分布式非关系型数据库,目前应用比较成熟,稳定,API操作比较简单,目前支持Python 2.7,还没有支持Python 3.x的包。
以下是我使用Python 2.7操作MongoDB的一些例子:
1.访问本地MongoDB
'''
Created on 2011-11-30
@author: LONMID
'''
import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
def main():
try:
c = Connection(host="localhost", port=27017)
except ConnectionFailure, e:
sys.stderr.write("Could not connect to MongoDB: %s" % e)
sys.exit(1)
# Get a Database handle to a database named "mydb"
dbh = c["mydb"]
dbh
# Demonstrate the db.connection property to retrieve a reference to the
# Connection object should it go out of scope. In most cases, keeping a
# reference to the Database object for the lifetime of your program should
# be sufficient.
assert dbh.connection == c
print "Successfully set up a database handle"
if __name__ == "__main__":
main()
2.插入操作:
'''
Created on 2011-11-30
@author: LONMID
'''
""" An example of how to insert a document """
import sys
from datetime import datetime
from pymongo import Connection
from pymongo.errors import ConnectionFailure
def main():
try:
c = Connection(host="localhost", port=27017)
except ConnectionFailure, e:
sys.stderr.write("Could not connect to MongoDB: %s" % e)
sys.exit(1)
dbh = c["mydb"]
assert dbh.connection == c
user_doc = {
"username" : "janedoe",
"firstname" : "Jane",
"surname" : "Doe",
"dateofbirth" : datetime(1974, 4, 12),
"email" : "janedoe74@example.com",
"score" : 0
}
dbh.users.insert(user_doc, safe=True)
print "Successfully inserted document: %s" % user_doc
if __name__ == "__main__":
main()
3.更新操作
'''
Created on 2011-11-29
@author: LONMID
'''
import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
import copy
def main():
try:
conn = Connection(host="localhost", port=27017)
print ("Connected Localhost successfully!!!!!")
dbh = conn["mydb"]
assert dbh.connection == conn
users = dbh.users.find_one({"username" : "janedoe"})
if not users:
print "no document found for username janedoe"
# else:
# for user in users:
# print user.get("username")
else:
for user in dbh.users.find(snapshot=True):
print user.get("username")
for user in dbh.users.find(snapshot=True):
print user.get("email"), user.get("score", 0)
old_user_doc = dbh.users.find_one({"username":"janedoe"})
new_user_doc = copy.deepcopy(old_user_doc)
# modify the copy to change the email address
new_user_doc["email"] = "janedoe74@example2.com"
# run the update query 更新操作
# replace the matched document with the contents of new_user_doc
dbh.users.update({"username":"janedoe"}, new_user_doc, safe=True)
except ConnectionFailure, e:
sys.stderr.write("Could not connect to MongoDB: %s" % e)
sys.exit(1)
if __name__ == "__main__":
main()
4.删除操作.
'''
Created on 2011-11-29
@author: LONMID
'''
import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
import copy
def main():
try:
conn = Connection(host="localhost", port=27017)
print ("Connected Localhost successfully!!!!!")
dbh = conn["mydb"]
assert dbh.connection == conn
users = dbh.users.find_one({"username" : "janedoe"})
if not users:
print "no document found for username janedoe"
# else:
# for user in users:
# print user.get("username")
else:
for user in dbh.users.find(snapshot=True):
print user.get("username")
for user in dbh.users.find(snapshot=True):
print user.get("email"), user.get("score", 0)
# Delete all documents in user collection with score 1
dbh.users.remove({"score":1}, safe=True)
# remove() will not raise any exception or error if no documents are matched.
# print "删除记录行的个数:\t"%count
except ConnectionFailure, e:
sys.stderr.write("Could not connect to MongoDB: %s" % e)
sys.exit(1)
if __name__ == "__main__":
main()
这些例子是参照 MongoDB & Python书箱写成的。
学习链接:
http://api.mongodb.org/python/2.0.1/tutorial.html
而MongoDB是一个由C++写的分布式非关系型数据库,目前应用比较成熟,稳定,API操作比较简单,目前支持Python 2.7,还没有支持Python 3.x的包。
以下是我使用Python 2.7操作MongoDB的一些例子:
1.访问本地MongoDB
'''
Created on 2011-11-30
@author: LONMID
'''
import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
def main():
try:
c = Connection(host="localhost", port=27017)
except ConnectionFailure, e:
sys.stderr.write("Could not connect to MongoDB: %s" % e)
sys.exit(1)
# Get a Database handle to a database named "mydb"
dbh = c["mydb"]
dbh
# Demonstrate the db.connection property to retrieve a reference to the
# Connection object should it go out of scope. In most cases, keeping a
# reference to the Database object for the lifetime of your program should
# be sufficient.
assert dbh.connection == c
print "Successfully set up a database handle"
if __name__ == "__main__":
main()
2.插入操作:
'''
Created on 2011-11-30
@author: LONMID
'''
""" An example of how to insert a document """
import sys
from datetime import datetime
from pymongo import Connection
from pymongo.errors import ConnectionFailure
def main():
try:
c = Connection(host="localhost", port=27017)
except ConnectionFailure, e:
sys.stderr.write("Could not connect to MongoDB: %s" % e)
sys.exit(1)
dbh = c["mydb"]
assert dbh.connection == c
user_doc = {
"username" : "janedoe",
"firstname" : "Jane",
"surname" : "Doe",
"dateofbirth" : datetime(1974, 4, 12),
"email" : "janedoe74@example.com",
"score" : 0
}
dbh.users.insert(user_doc, safe=True)
print "Successfully inserted document: %s" % user_doc
if __name__ == "__main__":
main()
3.更新操作
'''
Created on 2011-11-29
@author: LONMID
'''
import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
import copy
def main():
try:
conn = Connection(host="localhost", port=27017)
print ("Connected Localhost successfully!!!!!")
dbh = conn["mydb"]
assert dbh.connection == conn
users = dbh.users.find_one({"username" : "janedoe"})
if not users:
print "no document found for username janedoe"
# else:
# for user in users:
# print user.get("username")
else:
for user in dbh.users.find(snapshot=True):
print user.get("username")
for user in dbh.users.find(snapshot=True):
print user.get("email"), user.get("score", 0)
old_user_doc = dbh.users.find_one({"username":"janedoe"})
new_user_doc = copy.deepcopy(old_user_doc)
# modify the copy to change the email address
new_user_doc["email"] = "janedoe74@example2.com"
# run the update query 更新操作
# replace the matched document with the contents of new_user_doc
dbh.users.update({"username":"janedoe"}, new_user_doc, safe=True)
except ConnectionFailure, e:
sys.stderr.write("Could not connect to MongoDB: %s" % e)
sys.exit(1)
if __name__ == "__main__":
main()
4.删除操作.
'''
Created on 2011-11-29
@author: LONMID
'''
import sys
from pymongo import Connection
from pymongo.errors import ConnectionFailure
import copy
def main():
try:
conn = Connection(host="localhost", port=27017)
print ("Connected Localhost successfully!!!!!")
dbh = conn["mydb"]
assert dbh.connection == conn
users = dbh.users.find_one({"username" : "janedoe"})
if not users:
print "no document found for username janedoe"
# else:
# for user in users:
# print user.get("username")
else:
for user in dbh.users.find(snapshot=True):
print user.get("username")
for user in dbh.users.find(snapshot=True):
print user.get("email"), user.get("score", 0)
# Delete all documents in user collection with score 1
dbh.users.remove({"score":1}, safe=True)
# remove() will not raise any exception or error if no documents are matched.
# print "删除记录行的个数:\t"%count
except ConnectionFailure, e:
sys.stderr.write("Could not connect to MongoDB: %s" % e)
sys.exit(1)
if __name__ == "__main__":
main()
这些例子是参照 MongoDB & Python书箱写成的。
学习链接:
http://api.mongodb.org/python/2.0.1/tutorial.html
相关文章推荐
- python 使用mongodb 数据库操作
- Django使用Python操作数据库 --Django 1.8.2 文档(中文)部分笔记
- Python开发-pymongo的基本使用-mongoDB的操作
- Python操作数据库之Mongodb
- python操作mongodb之四cp数据库
- 在windows环境下使用Python操作spatialite数据库
- (转)[Python]MySQLdb for Python使用指南/Python的数据库操作【http://www.cnblogs.com/czh-liyu/archive/2008/04/13/1151758.html】
- Python操作MongoDB(PyMongo模块的使用)
- nosql数据库-mongodb-入门(2)--用python的pymongo 操作mongodb
- python使用SQL语句操作数据库中文乱码的解决
- Python学习之使用Python操作Redis数据库
- python数据库操作常用功能使用详解(创建表/插入数据/获取数据)
- python下使用pymongo操作mongodb
- Python使用pymongo操作mongodb
- Python使用pymongo模块操作MongoDB的方法示例
- Python:操作PostgreSQL数据库(使用DB API2.0)
- 使用Python2.7操作Selenium2时只打开浏览器不load URL的解决方法
- 使用python语言操作MongoDB
- Laravel框架数据库CURD操作、连贯操作使用方法