代码之家  ›  专栏  ›  技术社区  ›  PhilBot

Python MySQLdb在命令行上从Python工作,但不从Django Views.py工作

  •  -1
  • PhilBot  · 技术社区  · 7 年前

    >>> import MySQLdb
    >>> db = MySQLdb.connect(host="localhost",port=22,user="root",passwd="mypassword",db="gps")
    >>> 
    >>> cursor = db.cursor()
    

    如果我从django调试服务器运行它,它将失败:

    ERROR: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
    

    运行的代码如下所示:

    def getpos(request):
    
        query = "SELECT * FROM..."
    
        # connect to the DB and return nearby deals
        db = MySQLdb.connect(host="localhost",port=22,user="root",passwd="mypassword",db="gps")
        cursor = db.cursor()
    
        # Query the gps Data database
        results = cursor.execute(query)
        db.commit()
    

    为什么我可以在命令行上从Python进行连接,但不能使用Django在views.py文件中进行连接?谢谢

    我尝试过使用“127.0.0.1”而不是“localhost”,但似乎没有任何效果。谢谢你的帮助,谢谢!

    1 回复  |  直到 7 年前
        1
  •  1
  •   PhilBot    7 年前

    我必须将connect参数中的端口更改为host=“localhost”,port=3306。