介绍
介绍
福哥在使用pymysql的时候得到了如下的错误信息:
TypeError: __init__() takes 1 positional argument but 4 were given
意思是默认参数是一个,实际传入了4个。可是pymysql.connect一个参数怎么够用呢?
原因
原来在Python3.8里面pymysql.connect的定义这样的。
def __init__( self, *, user=None, # The first four arguments is based on DB-API 2.0 recommendation. password="", host=None, database=None, unix_socket=None, port=0, charset="", sql_mode=None, read_default_file=None, conv=None, use_unicode=True, client_flag=0, cursorclass=Cursor, init_command=None, connect_timeout=10, read_default_group=None, autocommit=False, local_infile=False, max_allowed_packet=16 * 1024 * 1024, defer_connect=False, auth_plugin_map=None, read_timeout=None, write_timeout=None, bind_address=None, binary_prefix=False, program_name=None, server_public_key=None, ssl=None, ssl_ca=None, ssl_cert=None, ssl_disabled=None, ssl_key=None, ssl_verify_cert=None, ssl_verify_identity=None, compress=None, # not supported named_pipe=None, # not supported passwd=None, # deprecated db=None, # deprecated ):
第一个参数是“*”,像host、user、password之类的参数都是默认参数形式了。
解决
解决办法就是只能显性地传递host、user、password之类的参数了。
# connection cn = pymysql.connect(host=mysqlHost, user=mysqlUser, passwd=mysqlPwd) cursor = cn.cursor() # select database cn.select_db(mysqlDb)
福哥感觉这个设计不太友好,毕竟我们调用pymysql.connect的参数都是在配置文件里面设置的,是否是默认值也不应该在它这里控制。