0
需要幫助來通過SQLALCHEMY連接到MySQL時發現問題。 下面是我的嘗試:通過SQLALCHEMY連接到Mysql的Python連接
from sqlalchemy import create_engine
import pandas
def return_connection_string(database_name, database_user, database_password, database_host, database_port):
try:
connection_string = 'mysql+mysqlconnector://' + database_user + ':' + database_password + '@' + database_host + ':' + database_port + '/' + database_name
print(connection_string)
return connection_string
except Exception as e:
print('Encountered error while generating connection string for MySQL!')
print(e)
def return_connection_object(database_name, database_user, database_password, database_host, database_port):
try:
connection_string = return_connection_string(database_name, database_user, database_password, database_host, database_port)
engine = create_engine(connection_string).connect()
return engine
except Exception as e:
print('Encountered error while connecting to MySQL database!')
print(e)
mysql_conn = return_connection_object('db_name', 'db_user', 'db_pass', 'xyz.abc.com', '4100')
df = pandas.read_sql_query('select distinct table_name from information_schema.tables', mysql_conn)
print(df.shape)
mysql_conn.close()
以上腳本的工作完全正常,並返回所需的輸出。 的問題是,當我嘗試基於類的方法如下:
from sqlalchemy import create_engine
import logging
class Connection_class(object):
def __init__(self):
pass
def return_connection_string(self, database_name, database_user, database_password, database_host, database_port):
try:
connection_string = 'mysql+mysqlconnector://' + database_user + ':' + database_password + '@' + database_host + ':' + database_port + '/' + database_name
print(connection_string)
return connection_string
except Exception as e:
print('Encountered error while generating connection string for MySQL!')
print(e)
def return_connection_object(self, database_name, database_user, database_password, database_host, database_port):
try:
connection_string = self.return_connection_string(database_name, database_user, database_password, database_host, database_port)
engine = create_engine(connection_string).connect()
return engine
except Exception as e:
print('Encountered error while connecting to MySQL database!')
print(e)
我包上面的類在一個名爲mysql軟件包。該main.py是如下:
from mysql import connector
import pandas
mysql_obj = connector()
mysql_conn = mysql_obj.return_connection_object('db_name', 'db_user', 'db_pass', 'xyz.abc.com', '4100')
df = pandas.read_sql_query('select distinct table_name from information_schema.tables', mysql_conn)
mysql_conn.close()
我得到的錯誤是: 對象類型「Connection_class」有沒有屬性「paramstyle」
在調試,我發現從return_connection_object功能發起的錯誤,不知何故,當它作爲腳本運行時,完全相同的函數返回連接對象時它返回null。
任何線索都會有幫助。提前致謝。