Skip to content

Instantly share code, notes, and snippets.

@dewitt4
Created August 15, 2023 18:00
Show Gist options
  • Save dewitt4/8e08657b2d569acdb17e4f1135154638 to your computer and use it in GitHub Desktop.
Save dewitt4/8e08657b2d569acdb17e4f1135154638 to your computer and use it in GitHub Desktop.
Python function that connects to a MySQL database, imports data into Pandas DataFrames, and then analyzes the data using OpenAI's API for natural language processing
import pandas as pd
import mysql.connector
import openai
# MySQL database settings
MYSQL_HOST = 'your_mysql_host'
MYSQL_USER = 'your_mysql_user'
MYSQL_PASSWORD = 'your_mysql_password'
MYSQL_DATABASE = 'your_mysql_database'
# OpenAI API key
OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY'
def analyze_data_with_openai(df):
openai.api_key = OPENAI_API_KEY
data_analysis_prompt = "Analyze the data in the DataFrame."
response = openai.Completion.create(
engine="davinci", prompt=data_analysis_prompt, max_tokens=100
)
analysis_result = response.choices[0].text
print("Data Analysis:")
print(analysis_result)
def import_mysql_data_and_analyze():
try:
connection = mysql.connector.connect(
host=MYSQL_HOST,
user=MYSQL_USER,
password=MYSQL_PASSWORD,
database=MYSQL_DATABASE
)
query = "SELECT * FROM your_table" # Modify the query based on your needs
df = pd.read_sql(query, connection)
print("Data Imported:")
print(df.head()) # Print the first few rows of the DataFrame
analyze_data_with_openai(df)
connection.close()
except Exception as e:
print(f'An error occurred: {e}')
if __name__ == '__main__':
import_mysql_data_and_analyze()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment