サンプル集  >  Python  >  PostgreSQL sqlalchemy 追加
PostgreSQL sqlalchemy 追加
2023/05/21

PostgreSQLへsqlalchemyでレコードを追加します。

◆環境
OS Windows 10 Home 22H2 64bit OS x64 プロセッサ
Python 3.9.6
VS Code 1.59.0

PostgreSQLのインストールとpythonのツールのインストールを行い最後にPythonでPostgreSQLへレコードを追加するプログラムを作成します。

  1. PostgreSQL検索とダウンロード
  2. PostgreSQLインストール
  3. PostgreSQL接続確認
  4. データベースとテーブルの作成
  5. sqlalchemyインストール
  6. プログラム作成

PostgreSQL検索

Googleでpostgresqlを検索します。


Downloadsをクリックします。


Windowsをクリックします。


Download the installerをクリックします。


15.3の行のWindows x86-64の列にある下矢印をクリックします。


以下のファイルがダウンロードされました。

postgresql-15.3-1-windows-x64.exe

PostgreSQLインストール

ダウンロードしたファイルを右クリックします。


「管理者として実行」をクリックします。


「Next」をクリックします。


「Next」をクリックします。


「Next」をクリックします。


「Next」をクリックします。


「Password」と「Retype password」を入力します。


「Next」をクリックします。


「Next」をクリックします。


「Next」をクリックします。


「Next」をクリックします。


「Next」をクリックします。


インストールが始まりました。


「Finish」をクリックします。


「Next」をクリックします。


「Next」をクリックします。


あまり関係なさそうなので「キャンセル」をクリックします。


「はい」をクリックします。

無事インストールできたようです。

PostgreSQL接続確認

コマンドプロンプトを開きPostgreSQLへの接続確認をします。

C:\>cd "\Program Files\PostgreSQL\15\bin"

C:\Program Files\PostgreSQL\15\bin>psql -U postgres
ユーザー postgres のパスワード:
psql (15.3)
"help"でヘルプを表示します。

postgres=# \q

正常に接続できました。

データベースとテーブルの作成

データベースとテーブルを作成します。

postgres=# create database mydb;
CREATE DATABASE

postgres=# \c mydb
データベース"mydb"にユーザー"postgres"として接続しました。
mydb=#

create table aisatsu(
    id serial not null,
    text text,
    primary key(id)
)

sqlalchemyインストール

sqlalchemyをインストールします


プログラム作成

作成したaisatsuテーブルにレコードを追加するプログラムを作成します。

psqlIns.py
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
42: 
43: 
44: 
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Integer, String

db_url="postgresql://" \
       "user:pass@localhost:5432/mydb"
print(db_url)

engine = create_engine(db_url)
print(engine)

db_session = scoped_session(
    sessionmaker(
        autocommit=False,
        autoflush=False,
        bind=engine
    )
)
print(db_session)

Base = declarative_base()
Base.query = db_session.query_property()

class aisatsu(Base):
    __tablename__ = "aisatsu"

    id = Column(Integer, primary_key = True, autoincrement=True)
    text = Column(String, unique=False)

    def __init__(self, text):
        self.text = text

def add_data():
    row = aisatsu(text='こんにちわ')
    db_session.add(row)
    row = aisatsu(text='おはよう')
    db_session.add(row)
    row = aisatsu(text='Hello')
    db_session.add(row)

    db_session.commit()

add_data()

MySQLのプログラムのdb_urlだけ変更しました。

実行してみます。

PS C:\pywork> py .\psqlIns.py
postgresql://user:pass@localhost:5432/mydb
Engine(postgresql://user:***@localhost:5432/mydb)
<sqlalchemy.orm.scoping.scoped_session object at 0x000002551B3FBD90>

特にエラーは出ませんでした。

データベースを確認してみます。

mydb=# select * from aisatsu;
 id |    text
----+------------
  1 | こんにちわ
  2 | おはよう
  3 | Hello
(3 行)

期待通りにデータが追加されていました。

▲ PageTop  ■ Home


Copyright (C) 2023 ymlib.com