Created
May 6, 2024 13:57
-
-
Save moriarty99779/6e484733843974d6fa560ae620bedc6c to your computer and use it in GitHub Desktop.
Python 3 MySQL Database Connection using MySQL Connector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mysql.connector | |
from mysql.connector import Error | |
try: | |
connection = mysql.connector.connect(host='database_server', | |
database='database_name', | |
user='database_username', | |
password='database_password') | |
if connection.is_connected(): | |
db_Info = connection.get_server_info() | |
cursor = connection.cursor() | |
cursor.execute("select database();") | |
record = cursor.fetchone() | |
print("You're connected to database: ", record) | |
except Error as e: | |
print("Error while connecting to MySQL", e) | |
finally: | |
if connection.is_connected(): | |
cursor.close() | |
connection.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment