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 stimport mysql.connectorfrom datetime import datetimefrom textblob import TextBlob# Koneksi ke MySQLconn = mysql.connector.connect(host='localhost',user='root',password='', # ganti sesuai MySQL kamudatabase='sentiment_db')cursor = conn.cursor()# UIst.title("Analisis Sentimen")komentar = st.text_area("Masukkan komentar:")if st.button("Analisa"):blob = TextBlob(komentar)polarity = blob.sentiment.polarityif polarity > 0:sentimen = 'Positif'elif polarity < 0:sentimen = 'Negatif'else:sentimen = 'Netral'# Simpan ke DBnow = 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 Riwayatst.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 selesaicursor.close()conn.close()
4. Jalankan Aplikasi
streamlit run streamlit_app.py
streamlit run streamlit_app.py
0 Komentar