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

时间:2018-06-28 19:10:47

标签: python mysql python-3.x class object

我正在尝试使用来自python的对象的示例创建数据库,但出现以下错误消息: “ AttributeError:'Eu'对象没有属性'translate'” 我不知道该如何解决

对不起,我的英语不是很好  这是我的代码:

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'

1 个答案:

答案 0 :(得分:0)

您不能将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)