mysql_exceptions.OperationalError : (2002, "Ca n't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'(2)") in Ubuntu 17.10
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()
MySQL DB가 로컬 호스트에서 작동하고 실제로 해당 사용자가 있습니까? SQL 셸에 로그인 할 수 있습니까?
편집 : 나는 파이썬 코드를 테스트했고 실제로 나를 위해 일했습니다 (매개 변수 = 'something', 큰 따옴표 및 하나의 인용 부호 있음). DB가 작동하지 않는 것 같습니다.
시작 했어? XAMP를 사용하지 않습니다 (Linux에서 사용하지 않는 것이 좋습니다). 다음 sudo apt install mysqlserver
명령을 사용하여 MySQL 서버 (XAMP없이)를 설치할 수 있습니다. 다음 명령으로 시작하십시오 systemctl start mysql.service/ service mysql start
. ps -ef | grep -i mysql
그런 다음 데몬이 실행 중인지 확인할 수 있습니다. 로그인을 시도 할 수 있습니다. mysql -u root -p
그 후 다음과 같이 DB 및 테이블을 생성 할 수 있습니다.
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
>>>
SRC :
https://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다