Airflow技术问题:使用MySqlHook获取连接报错求助
get_conn()时的tuple' object has no attribute 'get_conn'错误 Hey there, let’s troubleshoot this MySQL Hook issue you’re facing! That error usually pops up when the MySqlHook instance isn’t created correctly, so let’s break down what’s going wrong and how to fix it.
问题根源
The core issue here is that you’re using the wrong parameter name to initialize your MySqlHook. In Airflow’s MySqlHook, the parameter used to reference your saved connection ID (the one you named test_connection in the Web UI) is conn_id—not conn_name_attr. When you pass conn_name_attr='test_connection', the hook’s initialization logic malfunctions, returning a tuple instead of a proper MySqlHook instance. That’s why calling get_conn() throws an error: tuples don’t have that method.
快速解决方案
Fix the parameter name in your initialization code, and you should be good to go:
# Make sure you're importing the correct Hook first from airflow.providers.mysql.hooks.mysql import MySqlHook # Initialize the hook with the correct conn_id parameter mysql_hook = MySqlHook(conn_id='test_connection') conn = mysql_hook.get_conn()
额外排查步骤(如果问题仍存在)
If adjusting the parameter doesn’t fix things right away, check these boxes:
- Verify the Hook import: Ensure you’re importing the modern
MySqlHookfromairflow.providers.mysql.hooks.mysql(for Airflow 2.x). If you’re on Airflow 1.x, the import path isfrom airflow.hooks.mysql_hook import MySqlHook—but theconn_idparameter still applies. - Validate your Airflow connection: Head back to the Airflow Web UI, find your
test_connectionentry, and use the "Test" button to confirm it can successfully connect to your MySQL database. A misconfigured connection (wrong host, credentials, etc.) could cause unexpected behavior too. - Double-check
conn_name_attrusage: Just to clarify—conn_name_attris meant to reference an environment variable name that stores your connection ID, not the connection ID itself. For example, if you set an env var likeMY_DB_CONN=test_connection, you’d use it like this:
But this is only useful if you’re managing connections via environment variables instead of the Airflow UI.mysql_hook = MySqlHook(conn_name_attr='MY_DB_CONN')
内容的提问来源于stack exchange,提问作者Codutie

