Python 连接 MatrixOne 服务

MatrixOne 支持 Python 连接,在 0.6.0 版本中,MatrixOne 支持 pymysqlsqlalchemy 两种驱动程序。

本篇文档将指导你了解如何通过这两个 python 驱动程序连接 MatrixOne。

前期准备

  1. #检查 Python 版本号,确认是否安装
  2. python3 -V
  • 已安装 MySQL 客户端。

使用 pymysql 工具连接 MatrixOne 服务

PyMySQL 是一个纯 Python MySQL 客户端库。

  1. 下载安装 pymysql 和 cryptography 工具:

    1. pip3 install pymysql
    2. pip3 install cryptography
    3. #If you are in China mainland and have a low downloading speed, you can speed up the download by following commands.
    4. pip3 install pymysql -i https://pypi.tuna.tsinghua.edu.cn/simple
    5. pip3 install cryptography -i https://pypi.tuna.tsinghua.edu.cn/simple
  2. 使用 MySQL 客户端连接 MatrixOne。新建一个名称为 test 数据库:

    1. mysql> create database test;
  3. 创建一个纯文本文件 pymysql_connect_matrixone.py 并将代码写入文件:

    1. #!/usr/bin/python3
    2. import pymysql
    3. # Open database connection
    4. db = pymysql.connect(
    5. host='127.0.0.1',
    6. port=6001,
    7. user='dump',
    8. password = "111",
    9. db='test',
    10. )
    11. # prepare a cursor object using cursor() method
    12. cursor = db.cursor()
    13. # execute SQL query using execute() method.
    14. cursor.execute("SELECT VERSION()")
    15. # Fetch a single row using fetchone() method.
    16. data = cursor.fetchone()
    17. print ("Database version : %s " % data)
    18. # disconnect from server
    19. db.close()
  4. 打开一个终端,在终端内执行下面的命令:

    1. > python3 pymysql_connect_matrixone.py
    2. Database version : 8.0.30-MatrixOne-v0.6.0

使用 sqlalchemy 连接 MatrixOne

SQLAlchemy 是 Python SQL 工具包和对象关系映射器 (ORM),它为应用开发人员提供了 SQL 的全部功能。

  1. 下载并安装 sqlalchemy 工具,下载代码示例如下:

    1. pip3 install sqlalchemy
    2. #If you are in China mainland and have a low downloading speed, you can speed up the download by following commands.
    3. pip3 install sqlalchemy -i https://pypi.tuna.tsinghua.edu.cn/simple
  2. 使用 MySQL 客户端连接 MatrixOne。新建一个名称为 test 数据库,并且新建一个名称为 student 表,然后插入两条数据:

    1. mysql> create database test;
    2. mysql> use test;
    3. mysql> create table student (name varchar(20), age int);
    4. mysql> insert into student values ("tom", 11), ("alice", "10");
  3. 创建一个纯文本文件 sqlalchemy_connect_matrixone.py 并将代码写入文件:

    1. #!/usr/bin/python3
    2. from sqlalchemy import create_engine, text
    3. # Open database connection
    4. my_conn = create_engine("mysql+mysqldb://dump:111@127.0.0.1:6001/test")
    5. # execute SQL query using execute() method.
    6. query=text("SELECT * FROM student LIMIT 0,10")
    7. my_data=my_conn.execute(query)
    8. # print SQL result
    9. for row in my_data:
    10. print("name:", row["name"])
    11. print("age:", row["age"])
  4. 打开一个终端,在终端内执行下面的命令:

    1. python3 sqlalchemy_connect_matrixone.py
    2. name: tom
    3. age: 11
    4. name: alice
    5. age: 10