Contoh Koneksi Streamlit ke MySQL

1. Buat Database MySQL

CREATE DATABASE sentiment_db;

USE sentiment_db;

CREATE TABLE sentiment_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    text TEXT NOT NULL,
    sentiment VARCHAR(20),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
  
2. Install Library
     
     pip install streamlit mysql-connector-python


3. Contoh Aplikasi streamlit_app.py
Kode :
import streamlit as st
import mysql.connector
from datetime import datetime
from textblob import TextBlob

# Koneksi ke MySQL
conn = mysql.connector.connect(
    host='localhost',
    user='root',
    password='',  # ganti sesuai MySQL kamu
    database='sentiment_db'
)
cursor = conn.cursor()

# UI
st.title("Analisis Sentimen")
komentar = st.text_area("Masukkan komentar:")

if st.button("Analisa"):
    blob = TextBlob(komentar)
    polarity = blob.sentiment.polarity
    if polarity > 0:
        sentimen = 'Positif'
    elif polarity < 0:
        sentimen = 'Negatif'
    else:
        sentimen = 'Netral'

    # Simpan ke DB
    now = datetime.now()
    tanggal = now.date()
    jam = now.time()
    query = "INSERT INTO sentiment_log (tanggal, jam, komentar, sentimen) VALUES (%s, %s, %s, %s)"
    cursor.execute(query, (tanggal, jam, komentar, sentimen))
    conn.commit()

    st.success(f"Hasil Sentimen: **{sentimen}**")

# Tampilkan Riwayat
st.subheader("Riwayat Analisis")
cursor.execute("SELECT id, tanggal, jam, komentar, sentimen FROM sentiment_log ORDER BY id DESC")
data = cursor.fetchall()

for row in data:
    st.write(f"**{row[1]} {row[2]}** - {row[4]}: {row[3]}")

# Tutup koneksi saat aplikasi selesai
cursor.close()
conn.close()
4. Jalankan Aplikasi

streamlit run streamlit_app.py