我是python的新手,开始实现小程序,现在尝试连接数据库。我安装了python 3.4和mysql.connector 2.0.4。 下面给出的代码是我用来连接数据库的东西
#!"C:\python34\python.exe"
import sys
import mysql.connector
print("Content-Type: text/html;charset=utf-8")
print()
conn = mysql.connector.connect(host='localhost:8051',
database='test',
user='root',
password='tiger')
if conn.is_connected():
print('Connected to MySQL database')
但是我得到的错误如下所示。不明白为什么会发生这种错误,因为设置环境有误或者有其他原因 请建议
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\mysql\connector\network.py", line 448, in open_connection
socket.SOL_TCP)
File "C:\Python34\lib\socket.py", line 533, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11004] getaddrinfo failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#8>", line 2, in <module>
password='tiger',database='test')
File "C:\Python34\lib\site-packages\mysql\connector\__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "C:\Python34\lib\site-packages\mysql\connector\connection.py", line 95, in __init__
self.connect(**kwargs)
File "C:\Python34\lib\site-packages\mysql\connector\abstracts.py", line 719, in connect
self._open_connection()
File "C:\Python34\lib\site-packages\mysql\connector\connection.py", line 209, in _open_connection
self._socket.open_connection()
File "C:\Python34\lib\site-packages\mysql\connector\network.py", line 464, in open_connection
errno=2003, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:8051:3306' (11004 getaddrinfo failed)
答案 0 :(得分:2)
错误信息非常明确:
Can't connect to MySQL server on 'localhost:8051:3306'
请参阅双端口定义?
host='localhost:8051'
应该最喜欢
host='localhost', port='8051'
答案 1 :(得分:1)
您正在使用连接参数错误。我想你需要这样做:
conn = mysql.connector.connect(host='localhost',
port=8051,
database='test',
user='root',
password='tiger')
查看此doc了解更多详情。
答案 2 :(得分:0)
MySQL的默认端口是3306,当你没有通过&#34;端口&#34; mysql.connector.connect的参数它假设您使用的是默认端口3306,如果您使用另一个端口,则应该传递:
port=xxxx
到构造函数。
答案 3 :(得分:0)
对我来说,我在IDE中添加了所有连接器。
mysql连接器
mysql-connector-async-dd
mysql-connector-python
mysql-connector-python-dd
mysql-connector-repackaged
然后您可以在此处查看所有数据库名称:
import mysql.connector
mydb = mysql.connector.connect(host='localhost',user='root', passwd = 'Root@1234')
mycursor = mydb.cursor()
mycursor.execute("show databases")
for i in mycursor:
print(i)