MySQLdb connection problems

后端 未结 7 1026
逝去的感伤
逝去的感伤 2020-12-30 05:37

I\'m having trouble with the MySQLdb module.

db = MySQLdb.connect(
    host = \'localhost\', 
    user = \'root\', 
    passwd = \'\', 
    db = \'testdb\',          


        
相关标签:
7条回答
  • 2020-12-30 06:01

    Mysql uses sockets when the host is 'localhost' and tcp/ip when the host is anything else. By default Mysql will listen to both - you can disable either sockets or networking in you my.cnf file (see mysql.com for details).

    In your case forget about the port=3000 the mysql client lib is not paying any attention to it since you are using localhost and specify the socket as in unix_socket='path_to_socket'.

    If you decided to move this script to another machine you will need to change this connect string to use the actual host name or ip address and then you can loose the unix_socket and bring back the port. The default port for mysql is 3306 - you don't need to specify that port but you will need to specify 3000 if that is the port you are using.

    0 讨论(0)
  • 2020-12-30 06:05

    add unix_socket='path_to_socket' where path_to_socket should be the path of the MySQL socket, e.g. /var/run/mysqld/mysqld2.sock

    0 讨论(0)
  • 2020-12-30 06:07

    I had this issue where the unix socket file was some place else, python was trying to connect to a non-existing socket. Once this was corrected using the unix_socket option, it worked.

    0 讨论(0)
  • 2020-12-30 06:13

    Changing localhost to 127.0.0.1 solved my problem using MySQLdb:

    db = MySQLdb.connect(
        host = '127.0.0.1', 
        user = 'root', 
        passwd = '', 
        db = 'testdb', 
        port = 3000)
    

    Using 127.0.0.1 forces the client to use TCP/IP, so that the server listening to the TCP port can pickle it up. If host is specified as localhost, a Unix socket or pipe will be used.

    0 讨论(0)
  • 2020-12-30 06:17

    As far as I can tell, the python connector can ONLY connect to mysql through a internet socket: unix sockets (the default for the command line client) is not supported.

    In the CLI client, when you say "-h localhost", it actually interprets localhost as "Oh, localhost? I'll just connect to the unix socket instead", rather than the internet localhost socket.

    Ie, the mysql CLI client is doing something magical, and the Python connector is doing something "consistent, but restrictive".

    Choose your poison. (Pun not intended ;) )

    0 讨论(0)
  • 2020-12-30 06:18

    Maybe try adding the keyword parameter unix_socket = None to connect()?

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