import pandas as pd
df=pd.read_excel('student.xlsx',index_col='id') # DataFrame created using student file
from sqlalchemy import create_engine,text
from sqlalchemy.exc import SQLAlchemyError
path="sqlite:///my_data.db" # create a SQLite database in google colab session storage
my_conn = create_engine(path)
my_conn=my_conn.connect() # connection is established
try:
result = my_conn.execute(text("select name from sqlite_master where type = 'table'"))
for row in result:
print(row) # Display all tables in SQLite database
except SQLAlchemyError as e:
error = str(e.__dict__['orig'])
print(error)
df.to_sql(con=my_conn,name='student',if_exists='replace') # create student table in sqlite database
Check the list of tables available inside the SQLite database.
try:
result = my_conn.execute(text("SELECT name FROM sqlite_master WHERE type = 'table'"))
for row in result:
print(row) # List all tables in our SQLite database
except SQLAlchemyError as e:
error = str(e.__dict__['orig'])
print(error)
('student',)
From student table, display records.
result = my_conn.execute(text("SELECT * FROM student"))
for row in result:
print(row) # display row from student table.
df=pd.read_sql('SELECT * FROM student',my_conn,index_col='id')
print(df) # all rows of data
We can add conditions to our query and include only class = 'Five' while creating the DataFrame
df=pd.read_sql('SELECT * FROM student WHERE class="Five"',my_conn,index_col='id')
print(df) # All rows of class = 'Five'
Same code using Query part as string.
q="SELECT * FROM student WHERE class='Five'"
df=pd.read_sql(q,my_conn,index_col='id')
print(df)
class=Five ) as dictionary.
q="SELECT * FROM student WHERE class=:my_class"
df=pd.read_sql(q,my_conn,index_col='id',params={'my_class':'Five'})
We can pass multiple parameters as input to our query. Here we are creating the DataFrame by restricting the rows to Class =Five and mark is equal to or more than 80.
q="SELECT * FROM student WHERE class=:my_class AND mark >=:my_mark"
my_dict={'my_class':'Five','my_mark':80}
df=pd.read_sql(q,my_conn,index_col='id',params=my_dict)
print(df)
read_sql() function in Pandas to read data from a SQL database?read_sql() function?read_sql()?read_sql() function? If so, how?con parameter in the read_sql() function?read_sql() handle SQL queries that return multiple result sets?read_sql()?read_sql() with a PostgreSQL database?read_sql() when encountering NULL values in the database?read_sql() handle large datasets and memory usage?Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.