python - 如何从任何计算机编辑我的 MySQL 数据库?
问题描述
我创建了一个访问 MySQL 数据库的 Python 程序。它运行时的作用是将用户的 Logged_in 列编辑为 1,因此我知道该用户已登录。
UPDATE users SET logged_in = 1 WHERE username = "username";
完美运行。每次运行时,它都会编辑数据库,这样我就知道谁登录了。
问题是,它只适用于我的电脑。当其他人使用它时,它会说
DatabaseError: 2003 (HY000): Can´t connect to MySQL server on 'ip address'
我不明白我必须做什么才能使这个数据库可以从任何地方和任何人访问和编辑。
我很感激任何建议。
注意:我读过类似的问题,一个解决方案是让一台想要访问主机的计算机,但我需要这个数据库可以被运行程序的任何人编辑,所以我不会有他们计算机的信息。
简化代码:
import mysql.connector
#User inputs username and password in Tkinter GUI
username = "StackOverflow"
password = "123456"
def main():
#ACCESS DB
mydb = mysql.connector.connect(
host="my_computer_ip",
user="database_user",
password="password",
database = "users",
port=3306
)
#GET CURSOR (ALLOW TO EXECUTE COMMANDS)
mycursor = mydb.cursor()
#GET USER INFORMATION
mycursor.execute("SELECT username, password, logged_in FROM users WHERE
username = '{}';".format(username))
myresult = mycursor.fetchone()
#Display results if user is found.
if myresult is not None and len(myresult) > 0:
print("Connection Successful! \n User:{} \n Pass{}".format(myresult[0], myresult[1]))
else:
print("User does not exist.")
return False
# Next step is to match the input password to the one in the database,
# If they match, allow access to the GUI.
# Also, logged in column would be changed to 1 to let the database know the user is on.
main()
解决方案
您的数据库用户可能只能通过 localhost 访问。检查数据库用户和权限。如果您使用的是 MySQL Workbench,则可以运行此查询:
从 mysql.user 中选择用户、主机;
分配给数据库用户的主机应该是通配符 (%) 而不是localhost,以便在任何地方访问数据库。
要么创建另一个具有 % 主机的数据库用户,要么更新现有的用户。
CREATE USER 'database_user'@'%' IDENTIFIED BY 'password'; 或 UPDATE mysql.user SET host='%' WHERE user='database_user';
推荐阅读
- dictionary - Mapbox Power BI 圆形钻取
- javascript - 承诺未决,已履行不返回
- c# - SSIS 包调用 REST API 并存储在 SQL 表中
- python - 如何将 signal.py 错误消息呈现给 django-rest API?
- html - how to show div if input is checked, PURE CSS
- r - oneway.test 需要一个双边公式
- python - 从导入的单列文件创建嵌套列表
- haskell - 苍鹭在haskell中的方法
- javascript - “登录”未定义错误发生在 React.js
- c - 将文本文件列中的数据存储到数组中。在 C 中