我有以下简单的代码来测试我的Python Mysql连接。
connection = pymysql.connect(host = "localhost",
user = "root",
passwd = "",
db = "bugs",
charset = "utf8mb4",
cursorclass = "pymysql.cursors.Dictcursor")
try:
with connection.cursor() as cur:
cur.execute('''SELECT COUNT(*) FROM tbl_firefox''')
for row in cur.fetchall():
print("Number of rows in firefox table:", row)
connection.commit()
finally:
connection.close()
当我运行代码时,我收到类型错误
File "test2.py", line 31, in <module>
with connection.cursor() as cur:
File "C:\Program Files\Anaconda3\lib\site-packages\pymysql\connections.py", line 833, in cursor
return self.cursorclass(self)
TypeError: 'str' object is not callable
我一直在查看其他python-mysql代码中的类似错误。但仍然没有运气。如果有人能指出我的错误,非常感谢。
答案 0 :(得分:0)
引用PyMySQL:
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
它应该是密码而不是passwd,而cursorclass不是用引号
包围的