PDF (美國信紙尺寸) - 1.2Mb
PDF (A4) - 1.2Mb
使用 X DevAPI 時,使用文件集合相當簡單。下列範例顯示 CRUD 操作的基本用法(如需更多詳細資料,請參閱第 4.3 節,「集合 CRUD 函式概述」),在處理文件時:建立與 MySQL 伺服器執行個體的連線後,建立可容納 JSON 文件的新集合,並插入數個文件。然後,執行尋找操作以從集合中搜尋特定文件。最後,再次從資料庫中捨棄集合。範例假設 test
綱要存在,且集合 my_collection
不存在。
# Connecting to MySQL Server and working with a Collection
from mysqlsh import mysqlx
# Connect to server
mySession = mysqlx.get_session( {
'host': 'localhost', 'port': 33060,
'user': 'user', 'password': 'password'} )
myDb = mySession.get_schema('test')
# Create a new collection 'my_collection'
myColl = myDb.create_collection('my_collection')
# Insert documents
myColl.add({ 'name': 'Laurie', 'age': 19 }).execute()
myColl.add({ 'name': 'Nadya', 'age': 54 }).execute()
myColl.add({ 'name': 'Lukas', 'age': 32 }).execute()
# Find a document
docs = myColl.find('name like :param1 AND age < :param2') \
.limit(1) \
.bind('param1','L%') \
.bind('param2',20) \
.execute()
# Print document
doc = docs.fetch_one()
print(doc)
# Drop the collection
myDb.drop_collection('my_collection')