Python & My SQL
Python & My SQL
Installation:-
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password"
)
print(dataBase)
Creating Database
After connecting to the MySQL server let’s see how to create a MySQL
database using Python. For this, we will first create a cursor() object
and will then pass the SQL command as a string to the execute()
method. The SQL command to create a database is –
CREATE DATABASE DATABASE_NAME
Creating Tables
For creating tables we will follow the similar approach of writing the
SQL commands as strings and then passing it to the execute() method
of the cursor object. SQL command for creating a table is –
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
# 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()
# disconnecting from server
dataBase.close()
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
cursorObject.executemany(sql, val)
dataBase.commit()
dataBase = mysql.connector.connect(
host ="localhost",
user ="user",
passwd ="password",
database = "gfg"
)
myresult = cursorObject.fetchall()
for x in myresult:
print(x)