Informatics Practices
Consider following code when conn is the name of established connection to MySQL database.
Cars = {'Brand': ['Alto', 'Zen', 'City', 'Kia'],
'Price': [22000, 25000, 27000, 35000]}
df = pd.DataFrame(Cars, columns= ['Brand', 'Price'])
df.to_sql('CARS', conn, if_exists = 'replace', index = False)
What will be the output of following query if executed on MySQL ?
SELECT * from CARS ;
Answer
+-------+-------+
| Brand | Price |
+-------+-------+
| Alto | 22000 |
| Zen | 25000 |
| City | 27000 |
| Kia | 35000 |
+-------+-------+
Working
The code initializes a DataFrame df. It then writes this data to an SQL database table named 'CARS' using to_sql(). The SQL query SELECT * FROM CARS; retrieves all columns and rows from the 'CARS' table.
Related Questions
Write Python statement to export the DataFrame to a CSV file named data.csv stored at D: drive.
What is the difference between following two statements ?
(i)
df.to_sql('houses', con = conn, if_exists = 'replace')(ii)
df.to_sql('houses', con = conn, if_exists = 'replace', index = False)Consider following code when conn is the name of established connection to MySQL database.
sql = SELECT * from Sales where zone = "central"; df = pandas.read_sql(sql, conn) df.head()What will be stored in df ?
Write a program to read details such as Item, Sales made in a DataFrame and then store this data in a CSV file.