Develop a Python script that connects to a MySQL database, retrieves all records from a table named "products", and exports the data into a JSON file. The script should include error handling for common issues like connection errors and empty tables.
PLAINFORMAT
import json
import mysql.connector
from mysql.connector import Error

def connect_to_database():
    try:
        connection = mysql.connector.connect(
            host="your_host",
            user="your_user",
            password="your_password",
            database="your_database"
        )
        return connection
    except Error as e:
        print(f"Error connecting to database: {e}")
        return None

def get_products(connection):
    if not connection:
        return []

    cursor = connection.cursor()
    query = "SELECT * FROM products"

    try:
        cursor.execute(query)
        result = cursor.fetchall()

        column_names = [desc[0] for desc in cursor.description]
        products = [dict(zip(column_names, row)) for row in result]

        return products
    except Error as e:
        print(f"Error fetching products: {e}")
        return []
    finally:
        cursor.close()

def export_to_json(products):
    if not products:
        print("No products found")
        return

    try:
        with open("products.json", "w") as outfile:
            json.dump(products, outfile, indent=4, default=str)
        print("Products exported to products.json")
    except Exception as e:
        print(f"Error exporting products to JSON: {e}")

if __name__ == "__main__":
    connection = connect_to_database()
    products = get_products(connection)

    if connection:
        connection.close()

    export_to_json(products)