Connect to a database


Is it possible to connect to a database and query from it and visualise the data from it.

Thanks & Best Regards



Hi, Yes. It is possible. I was able to do it with SQL Server database.

Thanks a lot for your help.
Thanks & Best Regards

Is it possible to share a code snippet… How did you handle refresh when the database is updated with new data? I am very new to streamlit, and will appreciate a little help. Thanks

I created a class to handle my mySQL queries. It is just standard Python code for connecting to the database.

As for updates, if the database is being updated from an outside source, you will need to find a way to notify Streamlit of the change. I do my updates inside Streamlit - so I don’t have that problem.

import streamlit as st
import mysql.connector
from mysql.connector import errorcode

config = {
‘user’: ‘username’,
‘host’: ‘localhost’,
‘raise_on_warnings’: True

class mySQL:
def init(self, st): = st
self.cnx = mysql.connector.connect(**config)
self.cursor = self.cnx.cursor()

    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
  "Something is wrong with your user name or password")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
  "Database does not exist")
  'Unknown error')
def mysql_select(self, sql) :
    try :
        result = self.cursor.fetchall()
        if not result :
            return False, "Record not found"
        else :
            return True, result
    except mysql.connector.Error as err:
        return False, str(err.errno) + " : " + sql

thank you so very much.

Based on this class, how do I execute a query ?


you might also want to specify the database you want to use and whether it should be a local
one or hosted with a cloud provider(?).

In case of the latter, I highly recommend to check out the blogpost written by @AustinC. Streamlit ❤️ Firestore

@blob123, I guess you create a new mySQL class object of and then call the mysql_select function:

query_to_execute = """select * from table"""
mysql = mySQL(st)
mysql. mysql_select(query_to_execute)

Best regards