gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:05:17 24 4
gpt4 key购买 nike

我正在尝试在 python3 中执行以下脚本,该脚本假设连接到数据库,获取表列表,然后返回描述语句,但整个过程中 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)

这可能是前面描述的更改的错误,但我仍然无法得到解决方案

最佳答案

# 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

# [~]$

关于mysql - 通过python脚本执行mysql查询时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52039260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com