并非所有参数在python中的字符串格式化期间转换

时间:2014-05-20 09:52:28

标签: python mysql

我写了一个类似下面的方法

def schema_info1(self, mysql):
        """
        :type mysql: MySQL
        :param mysql: object
        """
        Logger().log("On Method: rds/mysql/schema.py-> schema_info")

        src_info = {}
        tables = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '%s'" % mysql.db
        columns = "SELECT count(column_name) FROM INFORMATION_SCHEMA.columns WHERE TABLE_SCHEMA='%s'" % mysql.db
        rows = "SELECT SUM(TABLE_ROWS) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='%s'" % mysql.db
        tablenames="SELECT TABLE_NAME  FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='%s'" % mysql.db
        columnnames="SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'etoh02unipk'AND table_schema = '%s'" %mysql.db
        sql = 'SELECT ( %s ) as tables, ( %s ) as columns, ( %s ) as rows, (%s ) as tablenames, (%s) as columnnames' \
              % (tables, columns, rows, tablenames, columnnames)
        res_row = mysql.query(sql)
        if res_row is not None:
            for r in res_row:
                src_info['tables'] = r['tables']
                src_info['columns'] = r['columns']
                src_info['rows'] = r['rows'] if r['rows'] is None else int(r['rows'])
                src_info['tablenames'] = r['tablenames']
                src_info['columnnames'] = r['coloumnnames']
        return src_info

Upto tablenames工作正常 当我试图让列名和数据类型变得像

columnnames="SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'etoh02unipk'AND table_schema = 'vgene'" %mysql.db
TypeError: not all arguments converted during string formatting

包含列名列表的表 我该如何解决上述问题

2 个答案:

答案 0 :(得分:1)

您没有要在该表达式中替换的字符串,这会导致异常。这与你这样做是一样的:

>>> w = 'world'
>>> 'hello' % w
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

字符串&#39;你好&#39;没有任何地方来格式化论点。

即使您解决了这个问题,也不应该在SQL中使用字符串解析。请阅读tutorial on the dbapi

答案 1 :(得分:0)

字符串中没有占位符。基本上,你说的是:

columnnames="foo" % mysql.db

并且Python很困惑:当你在字符串中没有%s时,为什么要提出论据呢?