0% found this document useful (0 votes)
57 views

Database

- Python allows connecting to databases through database APIs and makes operations like opening and closing connections easier compared to other languages. - The main steps to connect a Python application to a database are to import the connector module, create a connection object, create a cursor object, and execute queries. - MySQL can be connected to in Python by importing the MySQL connector module, using the connect() method to create a connection, and the cursor() method to execute queries and extract results.

Uploaded by

Syed Salman
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Database

- Python allows connecting to databases through database APIs and makes operations like opening and closing connections easier compared to other languages. - The main steps to connect a Python application to a database are to import the connector module, create a connection object, create a cursor object, and execute queries. - MySQL can be connected to in Python by importing the MySQL connector module, using the connect() method to create a connection, and the cursor() method to execute queries and extract results.

Uploaded by

Syed Salman
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

 

All these database can be accessed with their respective Python Application Program Interfaces
(APIs),

The database is a collection of prearranged information that can effortlessly be used, managed, revised.  The
key features of a DB API are,

•Create a database connection


•Work on SQL statements and stored procedures
•The connection can be closed
Benefits of Python for Database Programming

•Compared to other languages, python programming is faster and easy.


•In python, mandatory operations like opening and closing the database connections are carried out by python
itself. For all other programming languages, these types of operations are carried out specifically by the developer.
•The python database API’s support a wide extent of database setups, so it makes the task of connecting to the
databases a much easier process.
There are the following steps to connect a python application to our database.

1.Import mysql.connector module


2.Create the connection object.
3.Create the cursor object
4.Execute the query
How to Connect to MySQL Database in Python

Install MySQL connector module


Use the pip command to install MySQL connector Python.
pip install mysql-connector-python

Import MySQL connector module


Import using a import mysql.connector statement so you can use this module’s methods to
communicate with the MySQL database.

Use the connect() method


Use the connect() method of the MySQL Connector class with the required arguments to connect MySQL. It
would return a MySQLConnection object if the connection established successfully

Use the cursor() method


Use the cursor() method of a MySQLConnection object to create a cursor object to perform various SQL
operations.
Use the execute() method

The execute() methods run the SQL query and return the result.
executemany()
For all the listed parameters in the sequence, the given SQL statement is executed.

Extract result using to read query result


fetchone()
Fetch one row of a query output.
fetchmany()
Fetch a specific set of rows of a query result. the parameter specifies the number of rows per call.  The number of
rows being fetched largely depends on the involved array size of the cursor element. So as the number of rows
indicated in the parameter given, the same number of rows must be attempted to be fetched. If this is not capable
because of the specific rows available, then fewer rows may be returned.
.fetchall()
Fetch all the rows of a query. these rows are returned in a sequence. here the performance of the fetch could be
impacted at times by the cursor array fetch. When the cursor array size is extremely large, then the amount of time
taken to pull the rows will also be comparatively very high.

Close cursor and connection objects


use cursor.clsoe() and connection.clsoe() method to close open connections after your work completes
 connect MySQL database in Python

Arguments required to connect


The syntax to use the connect() is given below.
1.Connection-Object= mysql.connector.connect (host = <host-name> , user = <username> , passwd = <password> ) 

import mysql.connector  
  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")  
  
#printing the connection object   
print(myconn)  
 

Here, we must notice that we can specify the database name in the connect() method if we want to connect to a
specific database.
Example
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database = "mydb")  
Creating a cursor object
The cursor object can be defined as an abstraction specified in the Python DB-API 2.0. It facilitates us to have
multiple separate working environments through the same connection to the database. We can create the cursor
object by calling the 'cursor' function of the connection object. The cursor object is an important aspect of executing
queries to the databases.

The syntax to create the cursor object is given below.


<my_cur>  = conn.cursor()  

import mysql.connector  
#Create the connection object   
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database = "mydb")  
  
#printing the connection object   
print(myconn)   
  
#creating the cursor object  
cur = myconn.cursor()  
  
print(cur)  
Creating MySQL Database
To create a database, we will use CREATE DATABASE database_name statement and we will
execute this statement by creating an instance of the ‘cursor’ class.

import mysql.connector

mydb = mysql.connector.connect(
host = "localhost",
user = "yourusername",
password = "your_password"
)

cursor = mydb.cursor()

cursor.execute("CREATE DATABASE SJU")


If the database already exists then you will get an error, otherwise no error.

So make sure that the new database that you are creating does not have the same name as the
database already you created or exists previously.

Now to check the databases that you created, use “SHOW DATABASES” – SQL statement  i.e.
cursor.execute(“SHOW DATABASES”)

import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "1234"
)

cursor = mydb.cursor()

cursor.execute("SHOW DATABASE")

for x in cursor:
print(x)
Creating Tables
Now to create tables in a database, first, we have to select a database and for that,
we will pass database = “NameofDatabase” as your fourth parameter in connect() function.
Since we have created a database with the name SJU above, so we will use that and create our tables. We
will use CREATE TABLE gfg (variableName1 datatype, variableName2 datatype) statement to create our
table with the name ‘gfg’.

import mysql.connector

mydb = mysql.connector.connect(
host = "localhost",
user = "yourusername",
password = "your_password",
database = “sSJU"
)

cursor = mydb.cursor()

cursor.execute("CREATE TABLE gfg (name VARCHAR(255), user_name VARCHAR(255))")


If the table with the name ‘gfg’ already exists, you will get an error, otherwise no error.

So make sure that the new table that you are creating does not have the same name as the table
already you created or exists previously.

Now to check tables that you created, use “SHOW TABLES” – SQL statement i.e.
cursor.execute(“SHOW TABLES”)

import mysql.connector

mydb = mysql.connector.connect(
host = "localhost",
user = "root
password = "1234",
database = “SJU"
)
cursor = mydb.cursor()
cursor.execute("SHOW TABLES")

for x in cursor:
print(x)
•mysql.connector allows Python programs to access MySQL databases.

•connect() method of the MySQL Connector class with the arguments will connect to
MySQL and would return a MySQLConnection object if the connection is established
successfully.

•user = “yourusername”, here “yourusername” should be the same username as you


set during MySQL installation.

•password = “your_password”, here “your_password” should be the same password


as you set during MySQL installation.

•cursor() is used to execute the SQL statements in Python.

•execute() method is used to compile a SQL statement.


Inserting data
You can insert one row or multiple rows at once. The connector code is required to connect the commands to the
particular database. 

import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "username", Note:
password = "password", •The cursor() is used in order to iterate through the rows.
database = "database_name" •Without the command mydb.commit() the changes will not be
) saved.
mycursor = mydb.cursor()

sql = "INSERT INTO Student (Name, Roll_no) VALUES (%s, %s)"


val = ("Ram", "85")

mycursor.execute(sql, val)
mydb.commit()

print(mycursor.rowcount, "details inserted")

mydb.close()
To insert multiple values at once, executemany() method is used. This method iterates through the sequence of
parameters, passing the current parameter to the execute method.

sql = "INSERT INTO Student (Name, Roll_no) VALUES (%s, %s)"


val = [("Akash", "98"),
("Neel", "23"),
("Rohan", "43"),
("Amit", "87"),
("Anil", "45"),
("Megha", "55"),
("Sita", "95")]

mycursor.executemany(sql, val)
mydb.commit()

print(mycursor.rowcount, "details inserted")

mydb.close()
Update Clause
The update is used to change the existing values in a database. By using update a specific value can be corrected or
updated. It only affects the data and not the structure of the table.

import mysql.connector

mydb = mysql.connector.connect(
host ='localhost',
database ='College',
user ='root’,
)

cs = mydb.cursor()

statement ="UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'"

cs.execute(statement)
mydb.commit()

# Disconnecting from the database


mydb.close()

You might also like