python - 无法使用Python连接Mysql

标签 python mysql

我尝试使用简单的脚本 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 MysqlPython Mysql connection

关于python - 无法使用Python连接Mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58281100/

相关文章:

python - 错误 : "' dict' object has no attribute 'iteritems' "

python - 将 4 位整数转换为 boolean 列表

python - BeautifulSoup - 组合连续的标签

php - 如何使用 MySQL 以简单的增量更新 VARCHAR 值?

MySQL where 条件与 2 个值相交(逗号分隔)

python - 如何更改嵌套字典中的值

python - cgi.FieldStorage 始终为空 - 从不返回 POSTed 表单数据

java - spring boot 应用程序不启动

mysql - mysql 查询子句中反之亦然

MySQL BIGINT(20) 与 Varchar(31) 性能对比