PyMySQL can't connect to MySQL on localhost

后端 未结 8 1821
囚心锁ツ
囚心锁ツ 2020-11-28 08:26

I\'m trying to connect to MySQL on localhost using PyMySQL:

import pymysql
conn = pymysql.connect(db=\'base\', user=\'         


        
相关标签:
8条回答
  • 2020-11-28 08:27

    Two guesses:

    1. Run mysqladmin variables | grep socket to get where the socket is located, and try setting up a connection like so:

      pymysql.connect(db='base', user='root', passwd='pwd', unix_socket="/tmp/mysql.sock")
      
    2. Run mysqladmin variables | grep port and verify that the port is 3306. If not, you can set the port manually like so:

      pymysql.connect(db='base', user='root', passwd='pwd', host='localhost', port=XXXX)
      
    0 讨论(0)
  • 2020-11-28 08:29

    I solved the issue by replacing localhost with 127.0.0.1 and changing the password to my MYSQL database password as shown below;

    conn = pymysql.connect(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        passwd = 'XXXXXXXXX',
        db = 'mysql'
    )
    
    0 讨论(0)
  • 2020-11-28 08:31

    This worked for me:

    import pymysql
    
    db = pymysql.connect(host="localhost",port=8889,user="root",passwd="root")
    cursor=db.cursor()
    cursor.execute("SHOW DATABASES")
    results=cursor.fetchall()
    for result in results:
        print (result)
    

    if you want to find the port # go to mysql in terminal, and type:

    SHOW VARIABLES WHERE Variable_name = 'hostname';
    SHOW VARIABLES WHERE Variable_name = 'port';
    
    0 讨论(0)
  • 2020-11-28 08:40

    You need to add the port to the connection as well. Try this and it works fine.

    pymysql(Module Name).connect(host="localhost", user="root", passwd="root", port=8889, db="db_name")
    
    0 讨论(0)
  • 2020-11-28 08:43

    Seems like changing localhost to 127.0.0.1 fixes the error, at least in my configuration. If it doesn't, I would look for errors in tcp sockets connection and, of course, post it as a bug in pymysql bugtrack.

    0 讨论(0)
  • 2020-11-28 08:43

    I met the same question and my solution is as follows:

    1. Run ssh -fN -L 3307:mysql_host:3306 ssh_user@ssh_host in my terminal.
    2. Then input your ssh password
    3. conn = pymysql.connect(db='base', user='root', passwd='pwd', host='localhost')

    This error occurs because database does not support link directly.

    0 讨论(0)
提交回复
热议问题