Python 名称错误:名称';光标';没有定义
我正在尝试连接mysql并更改信息,但不起作用 main.pyPython 名称错误:名称';光标';没有定义,python,mysql,python-3.x,pymysql,Python,Mysql,Python 3.x,Pymysql,我正在尝试连接mysql并更改信息,但不起作用 main.py import pymysql def connect_setting(): # Trying to connect db_connection = None try: db_connection = pymysql.connect( user='db', passwd='password', host='127.0.0.1',
import pymysql
def connect_setting():
# Trying to connect
db_connection = None
try:
db_connection = pymysql.connect(
user='db',
passwd='password',
host='127.0.0.1',
db='test',
charset='utf8'
)
# If connection is not successful
except:
print("Can't connect to database")
return 0
# If Connection Is Successful
print("Connected")
# Making Cursor Object For Query Execution
global cursor
cursor = db_connection.cursor()
def get_off():
sql = '''INSERT INTO `-100`'''
cursor.execute(sql)
db_connection.commit()
index.py
from main import get_off as sql
sql()
错误
raceback(最近一次通话最后一次):
文件“/workspace/Kakao_points/index.py”,第3行,在
sql()
文件“/workspace/Kakao_points/main.py”,第30行,在get_off中
cursor.execute(sql)
NameError:未定义名称“游标”
我已经定义了游标,但不知何故python并没有在下一个def中获得信息。。有人请帮忙吗?连接失败时,您只需设置
光标
,因为您将这些行放在块中,除了:
块。这两行应该在try:
块中
您还需要将db\u连接设置为全局连接
global,以便在其他功能中使用它
def connect_setting():
global db_connection
# Trying to connect
db_connection = None
try:
db_connection = pymysql.connect(
user='db',
passwd='password',
host='127.0.0.1',
db='test',
charset='utf8'
)
# Making Cursor Object For Query Execution
global cursor
cursor = db_connection.cursor()
# If Connection Is Successful
print("Connected")
# If connection is not successful
except:
print("Can't connect to database")
return 0
只有在出现异常时才分配
cursor
。我确实更改了与您相同的错误名称,但仍然是相同的错误名称error:name'cursor'未定义您是否收到Connected
消息?是的,我还以为我没有打开mysql服务,但它已打开,python也打印“Connected”。我想不出原因。我更新了答案,说您还需要全局db_连接
,但这并不影响游标
。嗯,我仍然以另一种方式工作,但输出相同:C
def connect_setting():
global db_connection
# Trying to connect
db_connection = None
try:
db_connection = pymysql.connect(
user='db',
passwd='password',
host='127.0.0.1',
db='test',
charset='utf8'
)
# Making Cursor Object For Query Execution
global cursor
cursor = db_connection.cursor()
# If Connection Is Successful
print("Connected")
# If connection is not successful
except:
print("Can't connect to database")
return 0