A Simple Python Example Program for the MySQL Document Store

Last time we looked at a simple example program using the X Devapi and Node.JS. This time lets look at the Python version. Well, not actually the same. This time instead of looking for the Canadian record, the program limits the query to the first two records found.
Besides Python 2.7, you will need to install the Google Protobuf code plus the development release of the Python Connector and a recent version of MySQL 5.7.

The Code


import mysqlx

session = mysqlx.get_session({          # Authenticate to server
  'host':       'localhost',
  'port':       33060,
  'user':       'dstokes',
  'password':   'S3cR3t%'})

# Connect to Schema 'world_x'
schema = session.get_schema('world_x');

# Set collection to 'countryinfo'
collection = schema.get_collection('countryinfo')

# Ask for two records
result = collection.find().limit(2).execute()

docs = result.fetch_all()

# Print requested records
for i, data in enumerate(docs):
   print "{iteration}: {data}".format(iteration = i, data=data)

# Clean up
session.close()

A Note About the 'Collection' versus 'Table'

Take a quick peek at the table used for the example from the world_x database (see last entry for location and details for installation). There are actually two '_id's in the data. There is one that is the generated column you see below and the other is in the JSON column named doc. The collection itself is the JSON data. How to prove? Change the line starting with result in the above example and replace it with result = collection.find('GNP > 100000').limit(2).execute() or something similar with a key from the data.
mysql> desc countryinfo;
+-------+-------------+------+-----+---------+------------------+
| Field | Type        | Null | Key | Default | Extra            |
+-------+-------------+------+-----+---------+------------------+
| doc   | json        | YES  |     | NULL    |                  |
| _id   | varchar(32) | NO   | PRI | NULL    | STORED GENERATED |
+-------+-------------+------+-----+---------+------------------+
2 rows in set (0.00 sec)

Results


$python test.py
0: {"GNP": 828, "Name": "Aruba", "government": {"GovernmentForm": "Nonmetropolitan Territory of The Netherlands", "HeadOfState": "Beatrix"}, "demographics": {"LifeExpectancy": 78.4000015258789, "Population": 103000}, "_id": "ABW", "IndepYear": null, "geography": {"SurfaceArea": 193, "Region": "Caribbean", "Continent": "North America"}}
1: {"GNP": 5976, "Name": "Afghanistan", "government": {"GovernmentForm": "Islamic Emirate", "HeadOfState": "Mohammad Omar"}, "demographics": {"LifeExpectancy": 45.900001525878906, "Population": 22720000}, "_id": "AFG", "IndepYear": 1919, "geography": {"SurfaceArea": 652090, "Region": "Southern and Central Asia", "Continent": "Asia"}}

Next Time

Next time we will build on these two simple example programs.

Nhận xét

Bài đăng phổ biến từ blog này

Using MySQL to Output JSON

Pretty JSON with JSON_PRETTY()

Using find() with the MySQL Document Store

php


Save 50% on frames when you sign up for the GlassesShop.com newsletter!
Free Shipping At GlassesShop on orders $49+ ! No code required -
Weekly Deals starting at $6.95 plus an extra 20% off on orders $39+ At GlassesShop.com!
BUY ONE GET ONE FREE– use coupon code GSBOGO At GlassesShop.com - Ends 12/31/18
First Pair Free! Use Coupon Code FIRSTFREE At GlassesShop.com – Expires 12/31/2018
New Year, New Savings! Buy one Get one FREE! Use Code GSBOGO Details At GlassesShop.com
Best Buy Co, Inc.
Best Buy Co, Inc.
Best Buy Co, Inc.
button
banner
American National Standards Institute Inc.
SM_125x125button
SM_468x60banner
Iolo technologies, LLC
US/EU Warehouse Super Deal + Extra 10% OFF Code(GOFUN)
Up to 40% OFF + Extra 10% OFF Indoor & Patio Furniture(Code: fubuying)
Thousands of Car Accessories@TOMTOP.com
Thousands of Car Accessories@TOMTOP.com





























Seleção especial para os fãs de Harry Potter! Livros e artigos diversos inspirados na história de Harry, Hermione, Rony e cia!
Cupom exclusivo para os livros da série Harry Potter - CUPOM = POMODEOURO
Dia das crianças Submarino, até 10% off em brinquedos - CUPOM = VEMPROPLAY
10% off em telefonia - CUPOM = ALO10
Home
submarino.com.br
submarino.com.br
Planeta Criança - Diversos produtos com desconto para o Dia das Crianças
Zizo
banner
button
Lançamento FIFA 18 Edição Standard Microsoft Store Brazil
Lançamento FIFA 18 Edição Standard Microsoft Store Brazil




Contentmart
Hire - 468 x 60banner
Article in $3 - 125x125button
Os produtos mais vendidos na Multiar!
Home

Multiar
Home





Mochilas para Notebook Samsonite com Frete Grátis Sul e Sudeste
Conversor e gravador digital com Frete Grátis Brasil (exceto Norte)
Mouses HP com Frete Grátis Sul e Sudeste
WalmartBR
WalmartBR
WalmartBR
WalmartBR
HOMEPAGE
NOTEBOOKS
ALL IN ONE
IMPRESSORAS E SCANNERS
CARTUCHOS E TONERS
ACESSÓRIOS



Nossa melhor proteção para PC, Mac ou dispositivos móveis De R$ 109,00 por R$ 69,00
Nossa melhor proteção para todas as suas formas de se conectar De R$ 169,00 por R$ 99,00
Nossa melhor proteção, mais backup de PC e recursos de segurança da família para você e as pessoas importantes na sua vida De R$ 249,00 por R$ 139,00
Symantec Brazil
Symantec Brazil
Os produtos mais vendidos no ShopFácil!
HOME ShopFacil


eGlobal Central
GenericPro_1.jpgbanner
Relógios -5% de desconto no - CUPOM = FDA5-FBA4-582B-19D3




Informática