我正在尝试连接到mysql数据库,但遇到问题。我正在尝试使用mysql连接器(不确定这是否是最有效的库),但我遇到了错误。
这是我的基本脚本:
import mysql.connector
def test_sql_query():
db = mysql.connector.connect(host='hostname', database='db', user='dbuser', password='dbpass' port=000)
cur = db.cursor()
if db.is_connected():
print('Connected to MySQL database')
try:
sql_command = "select * from test where test like '%FileUploadAgent%' and status='00' order by test desc;"
cur.execute(sql_command)
db.commit()
rows = cur.fetchall()
for row in rows:
print " ", row[1][1]
except:
print "did not work"
db.close()
错误:
File "sql_test.py", line 44, in <module>
test_sql_query()
File "sql_test.py", line 6, in sterling_agent_sql_query
db = mysql.connector.connect("host='hostname.com' database='dbname' user='dbuser' password='dbpassword' port='000'")
File "/Library/Python/2.7/site-packages/mysql/connector/__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 57, in __init__
super(MySQLConnection, self).__init__(*args, **kwargs)
TypeError: __init__() takes exactly 1 argument (2 given)
我假设我连接错误。
答案 0 :(得分:1)
您传递给.connect()
的参数错误。你正在传递一个字符串。相反,每个都应该是他们自己的参数。
db = mysql.connector.connect(host='hostname',
database='db',
user='dbuser',
password='dbpass',
port=000)
此外,port
必须是整数,而不是字符串。我还假设您拥有的000
是示例数据。如果没有,那就无效了。
答案 1 :(得分:0)
您的连接格式不正确,将所有变量放在引号内使得该方法将其视为该方法的单个字符串输入。
db = mysql.connector.connect("host='hostname' database='db' user='dbuser' password='dbpass' port='000'")
应该是
db = mysql.connector.connect(
host='hostname',
database='db',
user='dbuser',
password='dbpass',
port=0)
请注意,您的端口值也应该是数据库的有效端口(不是回显端口)。
答案 2 :(得分:0)
我遇到了同样的问题,我的解决方案是卸载MySQL连接器。
python -m pip uninstall mysql-connector
然后使用以下命令重新安装它:
python -m pip install mysql-connector
它对我有用。