InvalidRequestError:VARCHAR在方言mysql上需要一个长度

时间:2013-05-09 23:17:28

标签: python mysql sql sqlalchemy

我正在尝试在运行12.04的Ubuntu机器上使用mysql创建一个远程数据库。

它有一个root用户,启用了远程登录,没有密码。我已经启动了服务器。

的输出
sudo netstat -tap | grep mysql

显示

tcp        0      0 localhost:mysql         *:*                     LISTEN      13246/mysqld

我创建了一个名为nwtopology的数据库(如上所述root还没有密码。)

 create database nwtopology
 grant all privileges on *.* to root@192.168.129.221
 FLUSH PRIVILEGES;

从运行Ubuntu 12.04的客户机上我使用python脚本使用sqlalchemy连接到远程mysql数据库。

from pox.core import core
import pox.openflow.libopenflow_01 as of
import re
import datetime
import time
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.expression import exists

log = core.getLogger()
engine = create_engine('mysql://root@192.168.129.139/nwtopology', echo=False)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()

class SourcetoPort(Base):
    """"""
    __tablename__ = 'source_to_port'
    id = Column(Integer, primary_key=True)
    port_no        = Column(Integer)
    src_address    = Column(String,index=True)

    #-----------------------------------------
    def __init__(self, src_address,port_no):
        """"""
        self.src_address = src_address
        self.port_no     = port_no


#create tables
Base.metadata.create_all(engine)

最后一行

Base.metadata.create_all(engine)

返回错误

 File "/usr/lib/python2.7/dist-packages/sqlalchemy/sql/compiler.py", line 1699, in visit_string
    return self.visit_VARCHAR(type_)
  File "/usr/lib/python2.7/dist-packages/sqlalchemy/dialects/mysql/base.py", line 1654, in visit_VARCHAR
    self.dialect.name)
InvalidRequestError: VARCHAR requires a length on dialect mysql

这是什么意思?如何在mysql上设置VARCHAR长度?我是sqlalchemy和mysql的新手。

1 个答案:

答案 0 :(得分:27)

将长度添加到String列:

src_address = Column(String(16), index=True)