如何在MySQL数据库中保存python对象?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (827)

我试图使用python中的对象示例创建一个数据库,但是我收到了错误消息,比如:“AttributeError:‘EU’Object没有属性‘Transform’”-我不知道如何修复它

这是我的代码:

import pymysql.cursors


class Eu:
    def __init__(self, nome='mel', idade=22):
        self.nome = nome
        self.idade = idade


eu = Eu()
nome = eu.nome
idade = eu.idade


# connect do database
conn = pymysql.connect(host='localhost',
                       user='root',
                       password='')

# create a cursor and a database
conn.cursor().execute('CREATE DATABASE banco73') 
conn.cursor().execute('USE banco73')

# create tables
conn.cursor().execute('CREATE TABLE tabela73 (eu BLOB)')

# use tables
conn.cursor().execute("""INSERT INTO tabela73 VALUES (?)""", (eu))

整个控制台消息:

runfile('C:/Users/Usuario/.spyder-py3/temp.py', wdir='C:/Users/Usuario/.spyder-py3')
Traceback (most recent call last):

  File "<ipython-input-59-9994dddea11c>", line 1, in <module>
    runfile('C:/Users/Usuario/.spyder-py3/temp.py', wdir='C:/Users/Usuario/.spyder-py3')

  File "C:\Users\Usuario\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "C:\Users\Usuario\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Usuario/.spyder-py3/temp.py", line 36, in <module>
    conn.cursor().execute("""INSERT INTO tabela73 VALUES (?)""", (eu))

  File "C:\Users\Usuario\Anaconda3\lib\site-packages\pymysql\cursors.py", line 168, in execute
    query = self.mogrify(query, args)

  File "C:\Users\Usuario\Anaconda3\lib\site-packages\pymysql\cursors.py", line 147, in mogrify
    query = query % self._escape_args(args, conn)

  File "C:\Users\Usuario\Anaconda3\lib\site-packages\pymysql\cursors.py", line 133, in _escape_args
    return conn.escape(args)

  File "C:\Users\Usuario\Anaconda3\lib\site-packages\pymysql\connections.py", line 839, in escape
    return converters.escape_item(obj, self.charset, mapping=mapping)

  File "C:\Users\Usuario\Anaconda3\lib\site-packages\pymysql\converters.py", line 27, in escape_item
    val = encoder(val, mapping)

  File "C:\Users\Usuario\Anaconda3\lib\site-packages\pymysql\converters.py", line 118, in escape_unicode
    return u"'%s'" % _escape_unicode(value)

  File "C:\Users\Usuario\Anaconda3\lib\site-packages\pymysql\converters.py", line 73, in _escape_unicode
    return value.translate(_escape_table)

AttributeError: 'Eu' object has no attribute 'translate'
提问于
用户回答回答于

不能直接将python对象存储在关系数据库中,你所做的就是存储数据可以用于在需要时重新生成对象。

有一些模块可以帮助解决这个问题,它们被称为ORM-对象-关系模型。

我推荐SQLAlchemy:

import sqlalchemy as sa
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine('mysql://root:pwd@localhost/banco73')
Base = declarative_base(bind=engine)
Session = sessionmaker(bind=engine)

class Eu(Base):
    __tablename__ = 'tabela73'

    id = Column(Integer(), primary_key=True)
    nome = Column(String(200))
    idade = Column(Integer())

    def __init__(self, nome='mel', idade=22):
        self.nome = nome
        self.idade = idade

Base.metadata.create_all() 
# automatically generates a create table: 
#CREATE TABLE tabela73 (
#   id INTEGER NOT NULL, 
#   nome VARCHAR(200), 
#   idade INTEGER, 
#   PRIMARY KEY (id)
#)

eu = Eu()

session = Session()
session.add(eu)
session.commit() # automatically generates the insert:
#INSERT INTO tabela73 (nome, idade) VALUES ('mel', 22)

扫码关注云+社区

领取腾讯云代金券