Database Connection

Write a Python program that attempts to connect to a database using given credentials. The program should handle exceptions for scenarios like incorrect credentials or the database server being unavailable.

Example 1:

Input: "correct_username", "correct_password", "correct_hostname"
Output: "Connection successful"

Example 2:

Input: "incorrect_username", "incorrect_password", "incorrect_hostname"
Output: "Exception: Connection failed due to incorrect credentials"

Use Python’s sqlite3 or mysql.connector module to connect to a database.

# Please replace sqlite3 with the relevant database module in actual scenario
import sqlite3

def connect_to_database(username, password, hostname):
    try:
        conn = sqlite3.connect('database.db')
        return "Connection successful"
    except sqlite3.Error as e:
        return "Exception: Connection failed due to incorrect credentials"

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!