Python 连接

MatrixOne 支持 Python 连接,支持 pymysql 和 sqlalchemy 两种驱动程序。

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

开始前准备

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

使用 pymysql 工具连接 MatrixOne 服务

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

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

``` 1. pip3 install pymysql 2. pip3 install cryptography

  1. If you are in China mainland and have a low downloading speed, you can speed up the download by following commands.

  2. pip3 install pymysql -i https://pypi.tuna.tsinghua.edu.cn/simple
  3. pip3 install cryptography -i https://pypi.tuna.tsinghua.edu.cn/simple ```
  4. 使用 MySQL 客户端连接 MatrixOne。新建一个名称为 test 数据库:

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

``` 1. #!/usr/bin/python3

  1. import pymysql

  2. Open database connection

  3. db = pymysql.connect(
  4. host='127.0.0.1',
  5. port=6001,
  6. user='dump',
  7. password = "111",
  8. db='test',
  9. )
  10. prepare a cursor object using cursor() method

  11. cursor = db.cursor()

  12. execute SQL query using execute() method.

  13. cursor.execute("SELECT VERSION()")

  14. Fetch a single row using fetchone() method.

  15. data = cursor.fetchone()
  16. print ("Database version : %s " % data)

  17. disconnect from server

  18. db.close() ```
  19. 打开一个终端,在终端内执行下面的命令:

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

使用 sqlalchemy 连接 MatrixOne

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

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

``` 1. pip3 install sqlalchemy

  1. If you are in China mainland and have a low downloading speed, you can speed up the download by following commands.

  2. pip3 install sqlalchemy -i https://pypi.tuna.tsinghua.edu.cn/simple ```
  3. 使用 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

  1. Open database connection

  2. my_conn = create_engine("mysql+mysqldb://dump:111@127.0.0.1:6001/test")

  3. execute SQL query using execute() method.

  4. query=text("SELECT * FROM student LIMIT 0,10")
  5. my_data=my_conn.execute(query)

  6. print SQL result

  7. for row in my_data:
  8. print("name:", row["name"])
  9. print("age:", row["age"]) ```
  10. 打开一个终端,在终端内执行下面的命令:

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