Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save moriarty99779/6e484733843974d6fa560ae620bedc6c to your computer and use it in GitHub Desktop.
Save moriarty99779/6e484733843974d6fa560ae620bedc6c to your computer and use it in GitHub Desktop.
Python 3 MySQL Database Connection using MySQL Connector
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