首页 > 解决方案 > 如何从任何计算机编辑我的 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()

标签: pythonmysql

解决方案


您的数据库用户可能只能通过 localhost 访问。检查数据库用户和权限。如果您使用的是 MySQL Workbench,则可以运行此查询:

从 mysql.user 中选择用户、主机;

分配给数据库用户的主机应该是通配符 (%) 而不是localhost,以便在任何地方访问数据库。

要么创建另一个具有 % 主机的数据库用户,要么更新现有的用户。

CREATE USER 'database_user'@'%' IDENTIFIED BY 'password'; UPDATE mysql.user SET host='%' WHERE user='database_user';


推荐阅读