首页 > 解决方案 > 尝试将多台计算机连接到 MySQL 服务器

问题描述

我不确定这是python问题还是mysql问题,但我希望能够使用python从另一台笔记本电脑连接到我的一台笔记本电脑上的mysql服务器。我打算让连接到服务器的笔记本电脑能够在连接时更改数据库中的任何内容,并能够从数据库中获取信息以显示在 GUI 上。我已经在托管 mysql 服务器的笔记本电脑上制作了 GUI,它完全按照我想要的方式工作,但现在我希望外部笔记本电脑也能在不托管服务器本身的情况下做同样的事情,我计划拥有多台计算机照着做。我想知道这样做的最佳方法是什么,因为我在网上查看过,我发现我可以通过下载 mysql 工作台然后从工作台连接到服务器来做到这一点,但我希望能够通过 python 做到这一点。下面是我用来连接 mysql 服务器的代码示例。我也在使用 pycharm 以防万一。

import mysql.connector  # make sure the python interpreter has 'mysql-connector-python' downloaded

# this sets up the connection to the mysql database where all the list information will be obtained from
mydb = mysql.connector.connect(host="xxx",
                               user="xxx",
                               passwd="xxx",
                               database="xxx"
                               )
mycursor = mydb.cursor()
mycursor.execute("select items from test where inuse = 0")
databaselistunsorted2 = [i[0] for i in # this makes the column turn its contents into a list for
                         mycursor.fetchall()]
# python
databaselist2 = databaselistunsorted2
print(databaselist2)

标签: pythonmysql

解决方案


这似乎是一个MySql问题。

您需要设置 MySql 以允许远程连接。

要对其进行测试,您可以检查具有 MySql 数据库的计算机上的端口 3306 是否打开,或者如果您从默认值更改,则将其设置为任何端口。

尝试从您最终想要使用 python 的计算机上运行它,就像测试一样,并首先让它工作。切换IP和用户等。需要允许您远程连接,这将帮助您验证这一点。

mysql -u user -h 192.168.1.28:3306 -p password

有关更多信息,请参阅:

连接到局域网中另一台 PC 上的 mysql 服务器

如果您在可以从命令行连接后在 python 中遇到错误,您可以运行它来查看错误是什么:

import mysql.connector
from mysql.connector import errorcode

try:
  cnx = mysql.connector.connect(user='scott', password='password',
                                 host='127.0.0.1',
                                 database='employees')
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with your user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
    print('It Worked!')
    cnx.close()

https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html

祝你好运!


推荐阅读