-
Notifications
You must be signed in to change notification settings - Fork 24
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1107 from yangj1211/sqlqlchemy
update use sqlalchemy connect mo
- Loading branch information
Showing
1 changed file
with
30 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 | ||
``` |