简体   繁体   English

Python无法连接到MySQL

[英]Python can't connect to MySQL

I'm trying to connect to a database on a Linux server, everything works fine with PHP using: 我正在尝试连接到Linux服务器上的数据库,使用以下命令在PHP上一切正常:

$mysqli= new mysqli($_DBHOST, $_DBUSER, $_DBPASS, $_DB);

I can also connect using the command line with: 我也可以使用命令行连接:

mysql -u xxx -p

But when I try to connect with Python using pymysql I get the following error: 但是,当我尝试使用pymysql与Python连接时,出现以下错误:

pymysql.err.InternalError: (1130, "Host 'xxx' is not allowed to connect to
this MariaDB server")

Python code: Python代码:

import pymysql
conn = pymysql.connect(host="xxx",user='xxx', passwd='xxx', db = 'xxx',
                                   ,port=3306, autocommit=True)

How can this even be possible? 怎么可能呢? It cannot be a permission issue since PHP can connect fine, or can it? 由于PHP可以很好地连接,所以这不是权限问题,还是可以?

Try this 尝试这个

    try:
        import mysql.connector
        mysql_connector = mysql.connector
    except:
        import pymysql
        mysql_connector = pymysql

    mysql_connector.connect(user='root', password='root', host='xxx:3306', database='test')

the best you can do is use MySQLdb (case sensitive) it's the best package. 最好的办法是使用MySQLdb(区分大小写),这是最好的软件包。 and then you can directly import your table in pandas dataframe. 然后您可以直接在pandas数据框中导入表格。

It's easy to do, but hard to remember the correct spelling: 这很容易,但是很难记住正确的拼写:

pip install MySQL-python

Note: Some dependencies might have to be in place when running the above command. 注意:运行上述命令时,某些依赖项可能必须存在。 Some hints on how to install these on various platforms: 关于如何在各种平台上安装这些的一些提示:

Ubuntu 14, Ubuntu 16, Debian 8.6 (jessie) Ubuntu 14,Ubuntu 16,Debian 8.6(jessie)

sudo apt-get install python-pip python-dev libmysqlclient-dev

Fedora 24: Fedora 24:

sudo dnf install python python-devel mysql-devel redhat-rpm-config gcc

Using MySQLdb 使用MySQLdb

import MySQLdb
conn = MySQLdb.connect(host="xxx.xxx.xx.x", user="name", passwd="password", db="database_name")
cursor = db.cursor()
import pandas as pd

df = pd.read_sql("select * from your_table",conn)

Two guesses: 两个猜测:

  1. Run mysqladmin variables | grep socket 运行mysqladmin variables | grep socket mysqladmin variables | grep socket to get where the socket is located, and try setting up a connection like so: mysqladmin variables | grep socket获取mysqladmin variables | grep socket所在的位置,然后尝试像这样建立连接:

     pymysql.connect(db='base', user='root', passwd='pwd', unix_socket="/tmp/mysql.sock") 
  2. Run mysqladmin variables | grep port 运行mysqladmin variables | grep port mysqladmin variables | grep port and verify that the port is 3306. If not, you can set the port manually like so: mysqladmin variables | grep port并确认端口为3306。如果不是,则可以手动设置端口,如下所示:

     pymysql.connect(db='base', user='root', passwd='pwd', host='localhost', port=XXXX) 

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

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