我尝试使用简单的脚本 python 连接 MySQL 数据库,但不成功。下面是我的代码,
[root@vn pyceaudio]# python
Python 2.7.5 (default, Aug 7 2019, 00:51:29)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
>>> cnx = mysql.connector.connect(host = 'hostname',database = 'testdb',user = 'test',password = 'test1234')
但我收到此错误,
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/site-packages/mysql/connector/__init__.py", line 172, in connect
return CMySQLConnection(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/mysql/connector/connection_cext.py", line 80, in __init__
self.connect(**kwargs)
File "/usr/lib64/python2.7/site-packages/mysql/connector/abstracts.py", line 780, in connect
self._open_connection()
File "/usr/lib64/python2.7/site-packages/mysql/connector/connection_cext.py", line 200, in _open_connection
self._cmysql.connect(**cnx_kwargs)
TypeError: function takes at most 14 arguments (15 given)
请给我建议并告诉我是否做错了。我对 Python 确实很陌生,而且仍在学习。顺便说一下,我在Centos7中使用的是Python2.7。
最佳答案
尝试运行此代码:
import mysql.connector
from mysql.connector import Error
try:
cnx = mysql.connector.connect(host = 'hostname',database = 'testdb',user = 'test',password = 'test1234')
if cnx.is_connected()://Runs if connection is established
db_Info = cnx.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = cnx.cursor()
cursor.execute("select database();")//executes query using cursor
record = cursor.fetchone()//fetches first data from above cursor
print("Your connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if (cnx.is_connected()):
cursor.close()
cnx.close()
print("MySQL connection is closed")
关于python - 无法使用Python连接Mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58281100/