python操作mysql与mongodb

Python 2018-12-29 1185

import pymysql

conn = pymysql.connect(host='localhost', user='root', password='huyu1680456489', port=3306, database='user')

cursor = conn.cursor()
sql = """
          insert into user(id, username, age) values (2, 'aaa', 15)"""
sql1 = """
    insert into user(id, username, age) values (null, %s, %s)
"""
username = 'dd'
age = 'fff'
cursor.execute(sql)
cursor.execute(sql1, (username, age))
conn.close()

sql2 = """
delete from user where id=2
"""
cursor.execute(sql2)
# 插入,删除,更新都要commit
conn.commit()
conn.close()
sql3="""
update table set user="dd" where
"""
"""
insert into user(id, aa, bb) values (?, ?, ?)
"""
cursor.close()
Python

mongo

# mongodb数据库
# 查看所有数据库
# show dbs
# db查看数据库
# database数据库
# 表叫collection/集合
# 数据行/文档 document
# column--sql,mongodb--field字段
# mongodb三元素
# 数据库、集合、文档
# 文档就是关系型数据库中的一行
# 集合就是关系型数据库中的表。可存储多个文档,结构不固定。
#####
# 基本命令
# db 查看当前数据库
# show dbs: 查看所有数据库
# use 数据库名
# db.dropDatabase():删除当前指向数据库
# db.集合名.insert(value) 添加数据到指定的集合中
# db.集合.find() 从指定的集合中查找数据
import pymongo
client = pymongo.MongoClient("127.0.0.1", port=27017)
db = client.zhihu
# 获取数据库中的集合,表
collection = db.qa
collection.insert({"name": "jfv", 'money': 88})

# 插入多条数据
collection.insert(
    {
        "username":'ddd',
    },
    {
        "username": 'ddvv',
    }
)
# 查所有数据
results = collection.find()
for i in results:
    print(i)
# 查找一条数据
result = collection.find_one()
# 或者是指定条件
result1 = collection.find_one({"username": "abc"})
print(result1)

# 更新一条文档对象
collection.update_one({"username": "abc"}, {"username":"aaa"})

# 更新多条文档对象,将username为abc的数据全部改为fvv
collection.update_many({"username": "abc"},{"$set":{"username":"fvv"}})
# 删除一条
collection.delete_one({"username": "dfdc"})
# 有密码的情况
```python
from pymongo import MongoClient
host = '?'
client = client.shujuku
db.authenticate("用户名", "密码")
collection = db.jihe
collection.insert({数据})
Python

 

标签:Python

文章评论

评论列表

已有0条评论