无法连接到本地 MySQL 服务器

无法连接到本地 MySQL 服务器

Ubuntu 17.10 中出现 mysql_exceptions.OperationalError: (2002, “无法通过套接字‘/var/run/mysqld/mysqld.sock’连接到本地 MySQL 服务器 (2)”)

安装 MySQL-python 和 XAMPP 后,我在 PyCharm 中编写了以下代码:

import MySQLdb

db = MySQLdb.connect("localhost","yara","yara","yara")

cursor = db.cursor()

cursor.execute("SELECT VERSION()")

data = cursor.fetchone()

print "Database version : %s " % data

db.close()

答案1

您确定 MySQL DB 在您的本地主机上运行并且确实有该用户吗?您能够登录 SQL shell 吗?

编辑:我测试了 Python 代码,它确实对我有用(带和不带参数='something',双引号和一个引号)。我认为您的数据库不起作用。

你启动了吗?我没有使用 XAMP(对我来说,不建议在 Linux 中使用它)。你可以使用sudo apt install mysqlserver命令安装 MySQL 服务器(不使用 XAMP),然后使用以下命令启动它:systemctl start mysql.service/ service mysql start 之后,你可以验证守护程序是否正在运行:ps -ef | grep -i mysql 然后你可以尝试登录:mysql -u root -p

之后,您可以像这样创建数据库和表:

mysql> Create Database Dance;
Query OK, 1 row affected (0,02 sec)

mysql> commit;
Query OK, 0 rows affected (0,00 sec)

mysql> use Dance;
Database changed
mysql> CREATE TABLE cats
    -> (
    ->   id              INT unsigned NOT NULL AUTO_INCREMENT, # Unique ID for the record
    ->   name            VARCHAR(150) NOT NULL,                # Name of the cat
    ->   owner           VARCHAR(150) NOT NULL,                # Owner of the cat
    ->   birth           DATE NOT NULL,                        # Birthday of the cat
    ->   PRIMARY KEY     (id)                                  # Make the id the primary key
    -> );
Query OK, 0 rows affected (0,14 sec)

mysql> INSERT INTO cats ( name, owner, birth) VALUES
    ->   ( 'Sandy', 'Lennon', '2015-01-03' ),
    ->   ( 'Cookie', 'Casey', '2013-11-13' ),
    ->   ( 'Charlie', 'River', '2016-05-21' );
Query OK, 3 rows affected (0,07 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> CREATE USER 'admin'@'localhost' IDENTIFIED BY 'password';
Query OK, 0 rows affected (0,07 sec)

mysql> GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
Query OK, 0 rows affected (0,00 sec)

mysql> RANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' WITH GRANT OPTION;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'RANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' WITH GRANT OPTION' at line 1
mysql> GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' WITH GRANT OPTION;
Query OK, 0 rows affected (0,00 sec)

mysql> commit;
Query OK, 0 rows affected (0,00 sec)

如果 DB 已启动并正在运行,则您编写了错误的代码,您可以在 MySqldb.connect() 中添加参数,如下所示:

>>> db=MySQLdb.connect(host='localhost',user='admin',passwd='password',db='Dance')
>>> cursor = db.cursor()
>>> cursor.execute("SELECT * FROM Dance.cats")
3L
>>> numrows = cursor.rowcount
>>> for x in range(0, numrows):
...     row = cursor.fetchone()
...     print row[0], "-->", row[1]
... 
1 --> Sandy
2 --> Cookie
3 --> Charlie
>>> 

来源:

https://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python

相关内容