Let 'CARS' is a DataFrame with the following fields- Id, Name, Price, Model, YearMaufacture, FuelType
Arrange the following code segment in correct order to read DataFrame 'df' from Database ('pd' is alias of pandas).
(A) import sqlalchemy
(B) engine=create_engine('mysql+pymysql://root:smsmb@localhost:3306/CARS')
(C) df=pd.read_sql_query('SELECT * FROM CARS', engine)
(D) print(df)
Let 'CARS' is a DataFrame with the following fields- Id, Name, Price, Model, YearMaufacture, FuelType
Arrange the following code segment in correct order to read DataFrame 'df' from Database ('pd' is alias of pandas).
(A) import sqlalchemy
(B) engine=create_engine('mysql+pymysql://root:smsmb@localhost:3306/CARS')
(C) df=pd.read_sql_query('SELECT * FROM CARS', engine)
(D) print(df)
Solution
(A) import sqlalchemy: the library must be imported before its functions can be used.
(B) engine=create_engine(...): creates the connection to the MySQL database CARS.
(C) df=pd.read_sql_query('SELECT * FROM CARS', engine): runs the query through the engine and stores the result in df.
(D) print(df): displays the DataFrame, which exists only after the query has run.
Options 2, 3 and 4: each uses something before it exists. The query needs the engine, the engine needs the import, and print needs df.
Related questions:
2026: 19 May Shift 1