how to connect a database in python code example
Example 1: connect python to mysql
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
port = 8888,
database='whatever db you want'
)
print(mydb)
Example 2: python3 mysql database access
import pymysql
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
db.close()
Example 3: mysql connection python
from sqlalchemy import types, create_engine
import pymysql
try:
conn = create_engine('mysql+pymysql://user:pass@IP/database_name')
print("MySQL Connection Sucessfull!!!!!!!!!!!")
except Exception as err:
print("MySQL Connection Failed !!!!!!!!!!!")
print(err)