通过python脚本执行mysql查询时出错

时间:2018-08-27 12:20:47

标签: mysql python-3.x

我正在尝试在python3中执行以下脚本,该脚本想连接到数据库,获取表列表,然后返回describe语句,但整个python似乎总是更改``for''并返回以下错误:

File "apka_baz.py", line 17, in <module>
    for result in cursor.execute(describe, smthn):
  File "/usr/local/lib/python3.7/site-packages/mysql/connector/cursor.py", line 559, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/local/lib/python3.7/site-packages/mysql/connector/connection.py", line 494, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "/usr/local/lib/python3.7/site-packages/mysql/connector/connection.py", line 396, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test_table'' at line 1

代码:

# Open database connection
db = conn.connect(user="sb",password="smtn",host="172.blabla",database="blabla")

# prepare a cursor object using cursor() method
cursor = db.cursor()
describe = ("show create table %s")

cursor.execute("SHOW TABLES")
for row in cursor.fetchall():
    smthn = (row[0],)
    print(describe % smthn)
    for result in cursor.execute(describe, smthn):
        print(result)
        for rows in cursor.fetchall():
            print(rows)

这可能是先前描述的更改的错,但我仍然找不到解决方法

1 个答案:

答案 0 :(得分:1)

# prepare a cursor object using cursor() method
cursor = db.cursor()
cursor.execute("SHOW TABLES")

for row in cursor.fetchall():

    # it seems like you want to iterate through all tables?
    # either way, I renamed smthn to "table" - look below:
    # smthn  = (row[0],)  

    for table in row:  # row contains one or more table names
        print("Found table: %s" % table)
        Q = "SHOW CREATE TABLE %s" % table  # here we compile the query
        print("Executing: '%s;' ...\n" % Q)  #

        # It's not a good practice to query (write into) the same cursor 
        # that you're reading at the same time. May cause issues. Use separate cursor:
        cursor2 = db.cursor()  
        # THE FOLLOWING WAS THE ROOT OF ALL EVIL:
        # for result in cursor.execute(describe, smthn):  

        # we only GET a single result (either query succeeded or not)
        result = cursor2.execute(Q)

        # go through all and display
        for row in cursor2.fetchall():
            print(" -- " + " \n ".join(row))

上面的示例在我的测试表上的输出:

[~]$ python3.6 python-mysql-test.py
Found table: test
Executing: 'SHOW CREATE TABLE test;' ...

-- test
CREATE TABLE `test` (
    `id` smallint(5) unsigned NOT NULL,
    `string` varchar(128) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1

# [~]$