🛠️ToolsShed

Generatore di INSERT SQL

Genera istruzioni SQL INSERT da dati tabulari.

Quote Style:
SQL Output

Domande Frequenti

Implementazione del Codice

# Generate SQL INSERT statements from a list of dicts
def generate_inserts(table, rows, batch=False):
    if not rows:
        return ""
    columns = ", ".join(rows[0].keys())
    def fmt(v):
        if isinstance(v, (int, float)):
            return str(v)
        return f"'{str(v).replace(chr(39), chr(39)+chr(39))}'"

    if batch:
        values = ",\n  ".join(
            "(" + ", ".join(fmt(v) for v in row.values()) + ")"
            for row in rows
        )
        return f"INSERT INTO {table} ({columns})\nVALUES\n  {values};"
    else:
        return "\n".join(
            f"INSERT INTO {table} ({columns}) VALUES ({', '.join(fmt(v) for v in row.values())});"
            for row in rows
        )

rows = [
    {"id": 1, "name": "Alice", "email": "alice@example.com"},
    {"id": 2, "name": "Bob",   "email": "bob@example.com"},
]
print(generate_inserts("users", rows, batch=True))

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.