简体   繁体   English

使用python连接到局域网数据库

[英]Connect to lan database using python

I have set up xampp to both of my PCs with success. 我已经在两台PC上成功安装了xampp。 When I try to connect to the localhost of PC 1 while I am on PC 1 through python, everything works fine. 当我通过python在PC 1上尝试连接到PC 1的本地主机时,一切正常。 But when I am trying to connect to PC 2 xampp sql I cant get a connection. 但是,当我尝试连接到PC 2 xampp sql时,无法连接。 I have cofigured xampp to accept connections from other devices in the lan and I can access it perfectly through my web browser but not from my python programm. 我将xampp配置为可以接受来自局域网中其他设备的连接,并且我可以通过Web浏览器完美访问它,而不能从python程序中访问它。

This is my code: 这是我的代码:

def GetResults(self):
        try:
            cnx = mysql.connector.connect(user='test', password= '123456', host='paraliass-pc', port='3306', database='test')
            cursor = cnx.cursor()
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                print("Something is wrong with your username or password")
                self.statusBar().showMessage("Wrong Username or Password")
            elif err.errno == errorcode.ER_BAD_DB_ERROR:
                print("Database does not exist")
                self.statusBar().showMessage("Database does not exist")

        if cnx :               
            print("Connected")
            self.statusBar().showMessage("Connected")

        cursor = cnx.cursor()
        cursor.execute("SELECT * FROM STAFF WHERE NAME LIKE '" + self.textEdit.text() + "%' OR SURNAME LIKE '" + self.textEdit.text() + "%'" + "OR RANK LIKE '" + self.textEdit.text() + "%'")

I am getting this error which does not appear when I am connecting to the same pc I am running the program on 我正在连接到运行该程序的同一台PC时未出现此错误

UnboundLocalError: local variable 'cnx' referenced before assignment

By the way, if i change the username or password on the localhost to be wrong on purpose, I get the same error. 顺便说一句,如果我故意更改本地主机上的用户名或密码是错误的,则会收到相同的错误。

You should consider granting privileges to connect remotely to MySQL, and bind MySQL to use the IP address and port of your choosing. 您应该考虑授予特权以远程连接到MySQL,并绑定MySQL以使用您选择的IP地址和端口。 By default, MySQL will only listen for connections via localhost/socket. 默认情况下,MySQL仅通过localhost / socket监听连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM