Python數據庫操作
Pymysql
說明
連接參數
pymysql的 connect 需要提供4個參數,可選2個參數
host, user, password, db, charset, cursorclass
地址,用戶名,用戶密碼,數據庫名,編碼,游標
使用方法
conn = pymysql.connect(host, user, password, db, charset, cursorclass)
使用上下文管理器對游標進行管理,確保數據庫指針被正確關閉回收資源
with conn.cursor() as cursor:
cursor.execute() # 用於執行 sql 語句
cursor.commit() # 對數據庫的修改要 commit 才能提交確定修改
常用函數說明
***使用cursor
游標進行調用 ***
fetchone()
:取返回數據的一個,從第一個開始,一個接一個,先1后2fetchall()
:取出所有獲取的數據fetchmany()
:有參數size,獲取指定size
大小的數據,如2,則獲取2個execute()
:執行sql語句的函數commit()
:execute
執行后,需要commit
提交事件修改到數據庫
官方例程
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) COLLATE utf8_bin NOT NULL,
`password` varchar(255) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
AUTO_INCREMENT=1 ;
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
MongoDB
根據菜鳥教程整理
1.概念解析
2.創建數據庫
3.刪除數據庫
4.創建集合
5.刪除集合
6.插入文檔
7.更新文檔
8.刪除文檔
9.查詢文檔
概念解析
SQL術語 | MongoDB術語 | 解釋 |
---|---|---|
database | database | 數據庫 |
table | collection | 數據庫表 |
row | document | 數據記錄行 |
column | field | 數據字段 |
index | index | 索引 |
table joins | 不支持 | 表連接 |
primary key | primary key | 主鍵, MongoDB自動將_id字段設置為主鍵 |
創建數據庫
語法
use DATABASE_NAME
:創建數據庫
show dbs
:查看所有數據庫
新創建的數據庫不會立刻顯示在數據庫列表
,需要往里面插入數據一些數據才會顯示
在MongoDB 中默認的數據庫為test
,如果你沒有創建新的數據庫,集合將存放在test
數據庫中
刪除數據庫
先切換到該數據庫,然后執行db.dropDatabase()
use DATABASE_NAME
db.dropDatabase()
命令db.dropDatabase()
刪除集合
1.先切換數據庫
2.顯示所有表格show tables
或show collections
3.選擇相應的collections
4.db.collection_name.drop()
命令db.collection.drop()
> use DATABASE_NAME
switch to db DATABASE_NAME
> show tables
site
> db.site.drop()
true
> show tables
創建集合
命令db.createCollection(name, options)
options參數可選
注意:在 MongoDB 中,你不需要創建集合。當你插入一些文檔時,MongoDB 會自動創建集合。
刪除集合
命令:db.collection.drop()
1.切換要刪除集合所在的數據庫
2.show collections
查看全部集合
3.使用命令db.collection.drop()
刪除集合
注意:如果成功刪除選定集合,則 drop() 方法返回 true,否則返回 false。
插入文檔
文檔的數據結構和JSON基本一樣。
所有存儲在集合中的數據都是BSON格式。
BSON是一種類json的一種二進制形式的存儲格式,簡稱Binary JSON。
命令db.COLLECTION_NAME.insert(document)
或db.COllECTION_NAME.save(document)
步驟
1.使用JSON數據格式表示存儲的數據,如{'name':'yuyu
}`,或許如以下代碼一樣,存儲於變量
> document=({title: "練習",
... descr:"數據庫",
... name:"yuge",
... url:"www.strongyu.top"});
{
"title" : "練習",
"descr" : "數據庫",
"name" : "yuge",
"url" : "www.strongyu.top"
}
2.存儲於相應的collection
中,如:db.yuyu.insert({'name': 'yuyu'})
或db.yuyu.save(document})
3.查看數據的命令db.col.find()
--col 是 collection 的名字
更新文檔
有兩種方法
- update()
- save()
update()方法
注意
1.要指明更新數據的字段名字和數據
2.默認只更新一條數據,即如果有多條相同的數據,需要指定參數設置
save()方法
傳入文檔,根據ObjectId
對原文檔進行覆蓋修改
刪除文檔
命令db.colllection.remove({query})
根據query
的條件對collection
的數據進行刪除,滿足query的則刪除
刪除collection
全部數據,即db.collection.remove({})
,即將query
置空
查詢文檔
命令db.collection.find()
Pymongo
個人練習代碼段
>>> from pymongo import MongoClient
>>> # 客戶端連接,演示本地連接
...
>>> client = MongoClient("localhost", 27017)
>>>
>>> db = client.web
>>> # web是演示的數據庫, db = client['web']
...
>>> data = {"author": "yuyuyu"
... , "text": "Hello MOngo",
... }
>>> db.yuyu.insert_one(data).inserted_id
ObjectId('5c5829aa0e059930be2e8bee')
# 已經插入,並返回了插入數據對應的 id 值
>>> import pprint
>>> pprint.pprint(db.yuyu.find_one())
>>> # find_one() 默認拿文檔的第一條數據,也可以指定條件進行獲取
>>> for data in db.yuyu.find():
... pprint.pprint(data)
...
{'_id': ObjectId('5c581717fbdb4fe8b28a4868'), '余偉': '喜歡寫代碼'}
{'123': 'abc', '_id': ObjectId('5c581892fbdb4fe8b28a486a')}
{'_id': ObjectId('5c5829aa0e059930be2e8bee'),
'author': 'yuyuyu',
'text': 'Hello MOngo'}
>>> # 使用 find() 方法遍歷 yuyu 文檔