есть скрипт, который использует sqlAlchemy и sqlite3. он отрабатывает без проблем: https://github.com/zlodiak/sql_alchemy_sqlite/blob/master/index.py
есть другой похожий скрипт, который использует sqlAlchemy и postgresql и он не отрабатывает(таблица создаётся, но она пустая):
import random
from sqlalchemy import create_engine, Table, MetaData, select, Column, String, Integer
from sqlalchemy.sql import and_, or_, not_
import psycopg2
engine = create_engine('postgresql://alchemy_user:qwerty@localhost:5432/db_alchemy')
connection = engine.connect()
metadata = MetaData()
quotes = Table('quotes', metadata,
Column('id', Integer, primary_key=True),
Column('text', Integer, nullable=False),
Column('weight', Integer, nullable=False)
)
metadata.create_all(engine)
quotes_json = []
with open("text.txt") as file_handler:
for line in file_handler:
quotes_json.append({
'text': line,
'weight': random.randint(1, 10),
})
connection.execute(quotes.insert(), quotes_json)
s = select([quotes]).where(and_(quotes.c.weight > 3, quotes.c.weight < 8))
result = connection.execute(s)
for row in result:
print(row['id'], row['text'][:20] + '...', row['weight'])
сообщение об ошибке следующее:
(simple_pg) md@md ~/.MINT18/code/python/alchemy/simple_pg $ python index.py
Traceback (most recent call last):
File "/home/md/.local/share/virtualenvs/simple_pg-epaYC0ys/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1225, in _execute_context
self.dialect.do_executemany(
File "/home/md/.local/share/virtualenvs/simple_pg-epaYC0ys/lib/python3.8/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py", line 854, in do_executemany
cursor.executemany(statement, parameters)
psycopg2.errors.InvalidTextRepresentation: invalid input syntax for integer: "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
"
LINE 1: INSERT INTO quotes (text, weight) VALUES ('Sed ut perspiciat...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "index.py", line 25, in <module>
connection.execute(quotes.insert(), quotes_json)
File "/home/md/.local/share/virtualenvs/simple_pg-epaYC0ys/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 982, in execute
return meth(self, multiparams, params)
File "/home/md/.local/share/virtualenvs/simple_pg-epaYC0ys/lib/python3.8/site-packages/sqlalchemy/sql/elements.py", line 293, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/home/md/.local/share/virtualenvs/simple_pg-epaYC0ys/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1095, in _execute_clauseelement
ret = self._execute_context(
File "/home/md/.local/share/virtualenvs/simple_pg-epaYC0ys/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1249, in _execute_context
self._handle_dbapi_exception(
File "/home/md/.local/share/virtualenvs/simple_pg-epaYC0ys/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1476, in _handle_dbapi_exception
util.raise_from_cause(sqlalchemy_exception, exc_info)
File "/home/md/.local/share/virtualenvs/simple_pg-epaYC0ys/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 398, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/home/md/.local/share/virtualenvs/simple_pg-epaYC0ys/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 152, in reraise
raise value.with_traceback(tb)
File "/home/md/.local/share/virtualenvs/simple_pg-epaYC0ys/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 1225, in _execute_context
self.dialect.do_executemany(
File "/home/md/.local/share/virtualenvs/simple_pg-epaYC0ys/lib/python3.8/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py", line 854, in do_executemany
cursor.executemany(statement, parameters)
sqlalchemy.exc.DataError: (psycopg2.errors.InvalidTextRepresentation) invalid input syntax for integer: "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
"
LINE 1: INSERT INTO quotes (text, weight) VALUES ('Sed ut perspiciat...
^
[SQL: INSERT INTO quotes (text, weight) VALUES (%(text)s, %(weight)s)]
[parameters: ({'text': 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. \n', 'weight': 8}, {'text': 'Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. \n', 'weight': 3}, {'text': 'Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. \n', 'weight': 10}, {'text': 'Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?\n', 'weight': 5}, {'text': 'Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?\n', 'weight': 5}, {'text': 'At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. \n', 'weight': 6}, {'text': 'Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. \n', 'weight': 7}, {'text': 'Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. \n', 'weight': 9}, {'text': 'Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.', 'weight': 4})]
(Background on this error at: http://sqlalche.me/e/9h9h)
я думал, что sqlAlchemy именно для того и существует чтобы скрывать особенности различных БД и работать с ними через единый интерфейс, а оказалось, что это не так. объясните пожалуйста почему я дурак?