From 4b52d20766effff799d6d646c7e6f5d4236759cb Mon Sep 17 00:00:00 2001 From: yangj1211 Date: Wed, 10 Jul 2024 18:08:14 +0800 Subject: [PATCH] update use sqlalchemy connect mo --- .../connect-mo/python-connect-to-matrixone.md | 52 +++++++++++-------- 1 file changed, 30 insertions(+), 22 deletions(-) diff --git a/docs/MatrixOne/Develop/connect-mo/python-connect-to-matrixone.md b/docs/MatrixOne/Develop/connect-mo/python-connect-to-matrixone.md index e01ed5957e..466cf42927 100644 --- a/docs/MatrixOne/Develop/connect-mo/python-connect-to-matrixone.md +++ b/docs/MatrixOne/Develop/connect-mo/python-connect-to-matrixone.md @@ -93,37 +93,45 @@ SQLAlchemy 是 Python SQL 工具包和对象关系映射器 (ORM),它为应用 ```sql mysql> create database test; mysql> use test; - mysql> create table student (name varchar(20), age int); - mysql> insert into student values ("tom", 11), ("alice", "10"); - + mysql> create table student (id int primary key,name varchar(20), age int); + mysql> insert into student values (1,"tom", 11), (2,"alice", "10"); ``` 3. 创建一个纯文本文件 *sqlalchemy_connect_matrixone.py* 并将代码写入文件: ```python - #!/usr/bin/python3 - from sqlalchemy import create_engine, text - - # Open database connection - my_conn = create_engine("mysql+mysqldb://root:111@127.0.0.1:6001/test") - - # execute SQL query using execute() method. - query=text("SELECT * FROM student LIMIT 0,10") - my_data=my_conn.execute(query) - - # print SQL result - for row in my_data: - print("name:", row["name"]) - print("age:", row["age"]) - + from sqlalchemy import create_engine + from sqlalchemy.orm import declarative_base as _declarative_base + from sqlalchemy import Column, Integer, String + from sqlalchemy.orm import sessionmaker + + #使用 SQLAlchemy 创建到 MatrixOne 的连接字符串,并创建一个引擎(Engine) + connection_string = 'mysql+pymysql://root:111@127.0.0.1:6001/test' + engine = create_engine(connection_string) + + Base = _declarative_base() + + #定义一个 Python 类来映射 student 表。 + class Student(Base): + __tablename__ = 'student' + id = Column(Integer, primary_key=True) + name = Column(String) + age = Column(Integer) + + #使用 sessionmaker 创建一个会话来执行查询 + Session = sessionmaker(bind=engine) + session = Session() + + #使用 SQLAlchemy 的查询接口来查询 student 表中的数据。 + users = session.query(Student).all() + for user in users: + print(f'ID: {user.id}, Name: {user.name}, Age: {user.age}') ``` 4. 打开一个终端,在终端内执行下面的命令: ``` python3 sqlalchemy_connect_matrixone.py - name: tom - age: 11 - name: alice - age: 10 + ID: 1, Name: tom, Age: 11 + ID: 2, Name: alice, Age: 10 ```