6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SQLAlchemy + MySQL を使ってみる(その2)

Last updated at Posted at 2016-05-29

前回の続きです。

チュートリアルに沿って進めていますが、最初にちょっとつまづいた以外はスムーズに進められたかなと思います。

それでも少し気になったところをメモしておきます。

カラムの文字数指定

MySQL の場合、必ずカラムの文字数を指定する必要があります。「sqlalchemy.Column()」のように省略することはできません。

sqlalchemy_test2.py
import sqlalchemy
import sqlalchemy.ext.declarative

Base = sqlalchemy.ext.declarative.declarative_base()

class Student(Base):
    __tablename__ = 'students'
    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    name = sqlalchemy.Column(sqlalchemy.String(20))
    kana = sqlalchemy.Column(sqlalchemy.String(40))

url = 'mysql+pymysql://root:@localhost/test_db?charset=utf8'

engine = sqlalchemy.create_engine(url, echo=True)

Base.metadata.create_all(engine)

[エラーメッセージ]
sqlalchemy.exc.CompileError: (in table 'students', column 'name'): Can't generate DDL for NullType(); did you forget to specify a type on this Column?

filter 関数の引数に渡す SQL 文

filter 関数の引数に渡す SQL 文は明示的に text 関数を使います。text 関数を使っていない場合、警告が発生します。

sqlalchemy_test3.py
import sqlalchemy
import sqlalchemy.orm
import sqlalchemy.ext.declarative
from sqlalchemy import text

Base = sqlalchemy.ext.declarative.declarative_base()

class Student(Base):
    __tablename__ = 'students'
    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    name = sqlalchemy.Column(sqlalchemy.String(20))
    kana = sqlalchemy.Column(sqlalchemy.String(40))
    
url = 'mysql+pymysql://root:@localhost/test_db?charset=utf8'

engine = sqlalchemy.create_engine(url, echo=False)

Session = sqlalchemy.orm.sessionmaker(bind=engine)
session = Session()

students = session.query(Student).filter("id=20") # SAWarning: Textual SQL expression
students = session.query(Student).filter(text("id=20"))

[警告メッセージ]
SAWarning: Textual SQL expression 'id=20' should be explicitly declared as text('id=20') (this warning may be suppressed after 10 occurrences) {"expr": util.ellipses_string(element)})

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?