mitulds / project_batch

This project is for the full-stack data science batch training
0 stars 0 forks source link

ENH: Databases #1

Open mitulds opened 8 months ago

mitulds commented 8 months ago

write a new python script to work with mysql databases as a first step of DE

PrathamDubey06 commented 8 months ago

As I understand, you want to create a Python code that can fetch, store, and access the data stored in a MySQL database.

To get started, you'll first need to install the mysql-connector library on your system. You can do this by opening the command prompt and running the following command:

pip install mysql-connector-python

After the mysql-connector is installed now you will need to implement the following code in your system.

`import mysql.connector

Step 1: Establish a connection to the MySQL database

def connect_to_mysql(): try: connection = mysql.connector.connect( host="your_host", user="your_user", password="your_password", database="your_database" ) print("Connected to MySQL successfully!") return connection except mysql.connector.Error as err: print(f"Error: {err}") return None

Step 2: Create a cursor to interact with the database

def create_cursor(connection): if connection: cursor = connection.cursor() return cursor else: return None

Step 3: Execute SQL queries

def execute_query(cursor, query): try: cursor.execute(query) print("Query executed successfully!") return True except mysql.connector.Error as err: print(f"Error: {err}") return False

Step 4: Fetch data from the database

def fetch_data(cursor): data = cursor.fetchall() return data

Step 5: Close cursor and database connection

def close_connection(connection, cursor): if cursor: cursor.close() if connection: connection.close() print("Connection closed.")

if name == "main": connection = connect_to_mysql() cursor = create_cursor(connection)

# Example queries
create_table_query = """
CREATE TABLE IF NOT EXISTS example_table (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255),
    age INT
)
"""
insert_data_query = """
INSERT INTO example_table (name, age) VALUES ('John', 30)
"""

if execute_query(cursor, create_table_query):
    execute_query(cursor, insert_data_query)

# Fetch and print data
select_data_query = "SELECT * FROM example_table"
if execute_query(cursor, select_data_query):
    data = fetch_data(cursor)
    for row in data:
        print(row)

close_connection(connection, cursor)`

Here, I assume that you already have MySQL installed on your system and have a basic understanding of it. If not, please let me know.