python-3.x - sqlalchemy 插入 - 不带编码的字符串参数

标签 python-3.x sqlalchemy pymysql

下面的代码在使用 Python 2.7 时有效,但在使用 Python 3.5 时引发 StatementError。我还没有在网上找到很好的解释。

为什么在这种情况下 sqlalchemy 不接受简单的 Python 3 字符串对象?有没有更好的方法向表中插入行?

from sqlalchemy import Table, MetaData, create_engine
import json

def add_site(site_id):
    engine = create_engine('mysql+pymysql://root:password@localhost/database_name', encoding='utf8', convert_unicode=True)
    metadata = MetaData()
    conn = engine.connect()
    table_name = Table('table_name', metadata, autoload=True, autoload_with=engine)

    site_name = 'Buffalo, NY'
    p_profile = {"0": 300, "1": 500, "2": 100}

    conn.execute(table_name.insert().values(updated=True,
                                    site_name=site_name, 
                                    site_id=site_id, 
                                    p_profile=json.dumps(p_profile)))

add_site(121)

编辑 该表之前是使用此函数创建的:

def create_table():
    engine = create_engine('mysql+pymysql://root:password@localhost/database_name')
    metadata = MetaData()

    # Create table for updating sites.
    table_name = Table('table_name', metadata,
        Column('id', Integer, Sequence('user_id_seq'), primary_key=True),
        Column('updated', Boolean),
        Column('site_name', BLOB),
        Column('site_id', SMALLINT),
        Column('p_profile', BLOB))

    metadata.create_all(engine)

编辑完整错误:

>>> scd.add_site(121)
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1073, in _execute_context
    context = constructor(dialect, self, conn, *args)
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/default.py", line 610, in _init_compiled
    for key in compiled_params
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/default.py", line 610, in <genexpr>
    for key in compiled_params
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/sql/sqltypes.py", line 834, in process
    return DBAPIBinary(value)
  File "/usr/local/lib/python3.5/dist-packages/pymysql/__init__.py", line 79, in Binary
    return bytes(x)
TypeError: string argument without an encoding

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/user1/Desktop/server_algorithm/database_tools.py", line 194, in add_site
    failed_acks=json.dumps(p_profile)))
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 914, in execute
    return meth(self, multiparams, params)
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/sql/elements.py", line 323, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1010, in _execute_clauseelement
    compiled_sql, distilled_params
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1078, in _execute_context
    None, None)
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1341, in _handle_dbapi_exception
    exc_info
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 202, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 185, in reraise
    raise value.with_traceback(tb)
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1073, in _execute_context
    context = constructor(dialect, self, conn, *args)
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/default.py", line 610, in _init_compiled
    for key in compiled_params
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/default.py", line 610, in <genexpr>
    for key in compiled_params
  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/sql/sqltypes.py", line 834, in process
    return DBAPIBinary(value)
  File "/usr/local/lib/python3.5/dist-packages/pymysql/__init__.py", line 79, in Binary
    return bytes(x)
sqlalchemy.exc.StatementError: (builtins.TypeError) string argument without an encoding [SQL: 'INSERT INTO table_name (updated, site_name, site_id, p_profile) VALUES (%(updated)s, %(site_name)s, %(site_id)s, %(p_profile)s)']

最佳答案

正如 univerio 提到的,解决方案是将字符串编码如下:

conn.execute(table_name.insert().values(updated=True,
                                    site_name=site_name, 
                                    site_id=site_id, 
                                    p_profile=bytes(json.dumps(p_profile), 'utf8')))

BLOB 需要二进制数据,因此在 Python 3 中我们需要 bytes,在 Python 2 中需要 str,因为 Python 2 字符串是字节序列。

如果我们想使用Python 3 str,我们需要使用TEXT而不是BLOB。

关于python-3.x - sqlalchemy 插入 - 不带编码的字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39112238/

相关文章:

python - Gmail API - ModuleNotFoundError : No module named 'googleapiclient' - Python 3. 7

python - 如何使用 python 比较同一数据框中的两列来创建新列?

python - 如何在sqlalchemy中加入同一个表

python - django.db.utils.InterfaceError : (0, '' )

python - PyMySQL 如何防止用户遭受 sql 注入(inject)攻击?

python - Airflow:如何将 PyMySQL 与 MySQL Hook 结合使用?

python - 将路径附加到路径

python - Python 脚本中的异常处理错误

python - 如何在 sqlalchemy 中选择没有答案的问题

python - 如果 SQLAlchemy 不存在对象,则插入对象的最快方法