notes mysql and python
notes mysql and python
Creating Databases
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password"
)
# creating database
cursorObject.execute("CREATE DATABASE gfg")
Creating Tables
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
# preparing a cursor object
cursorObject = dataBase.cursor()
# creating table
studentRecord = """CREATE TABLE STUDENT (
NAME VARCHAR(20) NOT NULL,
BRANCH VARCHAR(50),
ROLL INT NOT NULL,
SECTION VARCHAR(5),
AGE INT
)"""
# table created
cursorObject.execute(studentRecord)
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
cursorObject.execute(sql, val)
dataBase.commit()
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
cursorObject.executemany(sql, val)
dataBase.commit()
Fetching Data
In order to select particular attribute columns from a table, we write the attribute names.
In order to select all the attribute columns from a table, we use the asterisk ‘*’ symbol.
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
myresult = cursorObject.fetchall()
for x in myresult:
print(x)
Where Clause
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
myresult = cursorObject.fetchall()
for x in myresult:
print(x)
Order By Clause
Example: Order By clause in MySQL using Python
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
myresult = cursorObject.fetchall()
for x in myresult:
print(x)
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
for x in myresult:
print(x)
Update Data
Syntax:
UPDATE tablename
SET ="new value"
WHERE ="old value";
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
Syntax:
DELETE FROM TABLE_NAME WHERE ATTRIBUTE_NAME = ATTRIBUTE_VALUE
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
Drop Tables
Syntax:
DROP TABLE tablename;
DROP TABLE IF EXISTS tablename;
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
cursorObject.execute(query)
dataBase.commit()
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
cursorObject.execute(query)
dataBase.commit()