Skip to content

Commit

Permalink
update use sqlalchemy connect mo
Browse files Browse the repository at this point in the history
  • Loading branch information
yangj1211 committed Jul 10, 2024
1 parent 4f46afd commit 4b52d20
Showing 1 changed file with 30 additions and 22 deletions.
52 changes: 30 additions & 22 deletions docs/MatrixOne/Develop/connect-mo/python-connect-to-matrixone.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:[email protected]: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:[email protected]: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
```

0 comments on commit 4b52d20

Please sign in to comment.