developthou
developthou

Reputation: 363

Load mysqlsh module in python

I am writing the code in python to automate the innodb cluster provisioning. Based on this example https://dev.mysql.com/doc/dev/mysqlsh-api-python/8.0/group__mysql.html

mysql-py> from mysqlsh import mysql
 
// Then you can use the module functions and properties
// for example to create a session
mysql-py> mySession = mysql.get_classic_session('admin@localhost')

I was curious if there is a way to load mysqlsh module outside mysql shell.

For example

[Clang 12.0.5 (clang-1205.0.22.9)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from mysqlsh import mysql
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'mysqlsh'

Upvotes: 1

Views: 1187

Answers (2)

Amias Li
Amias Li

Reputation: 1

You can not import mysqlsh into python project. Because mysqlsh is not a simple python module.

However, you can change a way to use it.

For example, you can run your codes with mysqlsh insead of python. Then you can use the api in mysqlsh

https://github.com/AmiasLi/myshell-extend

Upvotes: 0

ranjjose
ranjjose

Reputation: 2148

The package you need is mysql-connector-python

Here's what worked for me:

Assuming you have sample datastore schema downloaded and imported world_x Database (You can get it from here)

  1. pip3 install mysql-connector-python
  2. >>> import mysqlx

Here's the full python snippet:

>> mySession = mysqlx.get_session( {
        'host': 'localhost', 'port': 33060,
        'user': 'root', 'password': '' } )
>>> myDb = mySession.get_schema('world_x')
>>> myColl = myDb.get_collection('countryinfo')
>>> myColl.find("Name = 'Australia'").execute().fetch_one()


{'GNP': 351182, '_id': '00005de917d8000000000000000e', 'Code': 'AUS', 'Name': 'Australia', 'IndepYear': 1901, 'geography': {'Region': 'Australia and New Zealand', 'Continent': 'Oceania', 'SurfaceArea': 7741220}, 'government': {'HeadOfState': 'Elizabeth II', 'GovernmentForm': 'Constitutional Monarchy, Federation'}, 'demographics': {'Population': 18886000, 'LifeExpectancy': 79.80000305175781}}

Upvotes: 1

Related Questions