Following is the program which will guide you on how to connect to a remote database in Python. For this first, you need to install the database connector and then use the following code.
You can install the connector with the following command:
$> pip install <your database connector MySQL/memsql>
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='<provide remote hostname here>',
database='<provide database name here>',
user='<userid>',
password='<password>')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_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()
print("MySQL connection is closed")
Comments
Post a Comment