91 lines
3.0 KiB
Python
91 lines
3.0 KiB
Python
import streamlit as st
|
||
import mysql.connector
|
||
from dotenv import load_dotenv
|
||
import os
|
||
from datetime import datetime
|
||
|
||
# Chargement des variables d'environnement
|
||
load_dotenv()
|
||
|
||
st.set_page_config(page_title="Insertion Mysql", layout="centered")
|
||
st.title("📄 Insertion dans SG.Emprunts")
|
||
|
||
# Connexion directe à la base SG
|
||
conn = mysql.connector.connect(
|
||
host=os.getenv("DB_HOST"),
|
||
user=os.getenv("DB_USER"),
|
||
password=os.getenv("DB_PASSWORD"),
|
||
database="Societe_Generale"
|
||
)
|
||
cursor = conn.cursor()
|
||
|
||
# Table fixe
|
||
table = "Emprunts"
|
||
|
||
# Lecture des colonnes de la table
|
||
cursor.execute(f"DESCRIBE {table}")
|
||
colonnes = cursor.fetchall()
|
||
|
||
# Détection de la clé primaire
|
||
cursor.execute(f"SHOW INDEX FROM {table} WHERE Key_name = 'PRIMARY'")
|
||
pk = cursor.fetchone()
|
||
primary_key = pk[4] if pk else None
|
||
|
||
# Sélection champ date
|
||
champ_date_candidates = [col[0] for col in colonnes if "date" in col[1].lower()]
|
||
champ_date = st.selectbox("Champ de date", champ_date_candidates)
|
||
|
||
# Paramètres d’insertion
|
||
nb_mois = st.number_input("Nombre d'insertions mensuelles", 1, 36, 6)
|
||
date_depart = st.date_input("Date de départ des insertions", value=datetime.today().date())
|
||
|
||
# Champs modifiables
|
||
champs_editables = [col for col in colonnes if col[0] != primary_key and col[0] != champ_date]
|
||
champs_choisis = []
|
||
st.subheader("Champs à insérer (hors clé primaire et champ de date)")
|
||
for col in champs_editables:
|
||
if st.checkbox(f"{col[0]} ({col[1]})", value=True):
|
||
champs_choisis.append(col[0])
|
||
|
||
# Formulaire principal
|
||
if champs_choisis:
|
||
with st.form(key="formulaire_emprunts"):
|
||
st.markdown("**Valeurs fixes pour les champs cochés**")
|
||
valeurs_fixes = {}
|
||
|
||
for champ in champs_choisis:
|
||
col_type = next((c[1] for c in colonnes if c[0] == champ), "").lower()
|
||
|
||
if "int" in col_type:
|
||
val = st.number_input(champ, step=1)
|
||
elif "decimal" in col_type or "float" in col_type:
|
||
val = st.number_input(champ, format="%.2f")
|
||
else:
|
||
val = st.text_input(champ)
|
||
|
||
valeurs_fixes[champ] = val
|
||
|
||
submit = st.form_submit_button("Insérer")
|
||
|
||
if submit:
|
||
try:
|
||
insert_count = 0
|
||
for i in range(nb_mois):
|
||
year = date_depart.year + (date_depart.month + i - 1) // 12
|
||
month = (date_depart.month + i - 1) % 12 + 1
|
||
day = min(date_depart.day, 28)
|
||
date_cible = datetime(year, month, day).date()
|
||
|
||
champs = [champ_date] + list(valeurs_fixes.keys())
|
||
valeurs = [date_cible] + list(valeurs_fixes.values())
|
||
sql = f"INSERT INTO {table} ({', '.join(champs)}) VALUES ({', '.join(['%s'] * len(valeurs))})"
|
||
|
||
cursor.execute(sql, valeurs)
|
||
insert_count += 1
|
||
|
||
conn.commit()
|
||
st.success(f"{insert_count} lignes insérées avec succès dans `{table}`.")
|
||
|
||
except Exception as e:
|
||
st.error(f"❌ Erreur lors de l’insertion : {e}")
|