gpt4 book ai didi

python - __init__() 正好接受 1 个参数,MYSQL

转载 作者:太空宇宙 更新时间:2023-11-03 11:50:46 25 4
gpt4 key购买 nike

我知道有人问过同标题的问题,但我无法根据给出的解决方案找出问题所在。我正在使用 argparser 连接到数据库并获取数据。这里

import os
import logging
import argparse
import mysql.connector

def main():
parser = create_parser()
args = parser.parse_args()
query_result = get_name_and_id(args.user, args.password, args.host, args.database)

def create_parser():
parser = argparse.ArgumentParser(description="Require database credentials")
parser.add_argument("--host", required="True", metavar="[host]", dest='host', help="Database host")
parser.add_argument("--database-name", required="True", metavar="[database]", dest='database', help="Name of the database to connect to.")
parser.add_argument("--user-name", metavar="[user]", dest='user', required="True")
parser.add_argument("--password", required="True", metavar="[password]", dest='password')
return parser

def get_name_and_id(user,password,host,database):
con = mysql.connector.connect(user, password, host, database)
cursor = con.cursor()
query = ("SELECT id, name FROM some_table")
cursor.execute(query)
name_id_list = dict()
for id, name in cursor:
name_id_list[id] = name
return name_id_list

if __name__ == "__main__":
main()

要运行这个程序,我使用命令python test_database.py --host somehost --database somedb --user-name myuser-name --password 我的密码

这是堆栈跟踪:

File "test_arg_parsing.py", line 59, in main() File "test_arg_parsing.py", line 14, in main query_result = get_name_and_id(args.user, args.password, args.host, args.database) File "test_arg_parsing.py", line 32, in get_enqueuer_data con = mysql.connector.connect(user, password, host, database) 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 (5 given)

这里我不明白的是它是否在提示 MySQLConnection init 函数?或者我没有运行正确的命令?我已经使用 mysql 连接器成功连接到同一个数据库。但我现在想将凭据作为参数传递。这里出了什么问题?

最佳答案

这些必须是关键字参数。尝试:

con = mysql.connector.connect(user=user, password=password, host=host, database=database)

关于python - __init__() 正好接受 1 个参数,MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35615578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com