Skip to content

Instantly share code, notes, and snippets.

@CyanGirl
Created May 22, 2021 08:10
Show Gist options
  • Save CyanGirl/2c2609d81546298268566cb361f72c8a to your computer and use it in GitHub Desktop.
Save CyanGirl/2c2609d81546298268566cb361f72c8a to your computer and use it in GitHub Desktop.
Creating the Database connectivity and executing queries
"""
1. Install mysql-connector-python
2. import the package
3. create the db connector and printing it will give you the object.
if you dont pass the DB name , it will connect to the entire database
4. cReate a DB cursor and pass queries to it.
5. Creating a new Database: CREATE DATABASE testDB;
6. the Db cursor will hold all the data and if command executed succesfully
the returned value will be NONE.
"""
import mysql.connector
import getpass
def connectDB():
print("\nConnect to the Database or MySql:\n")
hostname=input("Enter Hostname: ")
username=input("Enter Username: ")
passwordn=getpass.getpass("Enter Password: ")
dbname=input("Enter Database Name: [Can be left empty] ")
if len(dbname)<1:
mydb=mysql.connector.connect(
host=hostname,
user=username,
password=passwordn
)
else:
mydb=mysql.connector.connect(
host=hostname,
user=username,
password=passwordn,
database=dbname
)
print ("Connected to the Database : ",mydb)
mycursor=mydb.cursor()
print("\nEntering Interactive Mode\n\t TO EXIT ENTER 5 or Ctrl+C\n")
while True:
query=input("\t>> ")
if query=='5':
print("\nCommiting..")
mydb.commit()
break
mycursor.execute(query)
output=mycursor.fetchall()
print(output)
if __name__=='__main__':
connectDB()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment