Interface python with sql database10.pdfHiteshNandi
This document provides information about interfacing Python with SQL databases. It discusses using Python's Database API to connect to databases like MySQL and perform SQL queries. Specific topics covered include establishing a connection, creating a cursor object to execute queries, creating/modifying tables, and inserting/searching/fetching records from tables at runtime. The document aims to demonstrate how to interface a Python program with a backend SQL database.
Interfacing python to mysql (11363255151).pptxcavicav231
This document discusses how to interface Python with a MySQL database. It provides steps to install the MySQL connector module in Python, create a connection to a MySQL database, execute queries using a cursor, extract data from the result set, and close the connection. The key steps are to import the MySQL connector module, use it to connect to a MySQL database, create a cursor to execute queries, fetch and extract data using methods like fetchall(), fetchmany(), and fetchone(), and finally close the connection. Parameterized queries and committing transactions are also covered.
This document discusses interfacing Python with MySQL databases. It introduces MySQL Connector Python, which is a Python module for communicating with MySQL databases. The key steps covered are:
1. Installing MySQL Connector Python using pip or from source code.
2. Connecting to a MySQL database from Python by calling the connect() method and passing required parameters like username, password, host, and database name.
3. Using the connection object returned to create a cursor object to execute SQL queries and extract result data.
4. Closing the cursor and connection when done to clean up resources.
PythonDatabaseAPI -Presentation for Databasedharawagh9999
Python DB API allows Python applications to interact with relational databases in a uniform way. It supports various databases including SQLite, MySQL, PostgreSQL, Oracle, and SQL Server. The document discusses connecting Python to MySQL, executing SQL queries, and fetching data. It provides code to connect to a MySQL database, create a table, insert sample data, run queries, and display results.
This document provides instructions for connecting to a MySQL database from a C++ application using MySQL Connector/C++. It discusses installing the MySQL Connector/C++ driver, making a connection to a MySQL database, executing queries to retrieve and insert data, and closing the connection. Sample C++ code is provided to demonstrate connecting to a database, running queries, processing result sets, and disconnecting.
Www Kitebird Com Articles Pydbapi Html Toc 1AkramWaseem
The document discusses using Python and the DB-API module to write scripts that interact with MySQL databases. It provides an example of a short script that connects to a MySQL database, issues a query to get the server version, and prints the result. It then discusses a more extensive script that handles errors, issues different statement types like INSERT and SELECT, and retrieves result rows using fetchone() and fetchall() methods. The document provides information on installing prerequisites like Python and MySQLdb, and executing the example scripts.
This document discusses connecting Python to a MySQL database. It introduces database programming in Python and the Python DB API interface. It then provides 7 steps to connect to a MySQL database using the MySQL Connector Python package, including importing the package, opening a connection, creating a cursor, executing queries, extracting the result set, and closing the connection.
The document discusses writing MySQL scripts using Python's DB-API module. It provides a short 3-sentence summary of the document:
1) Python's DB-API module provides a database application programming interface and the MySQLdb driver allows it to access MySQL databases.
2) An example script is presented that connects to a MySQL database, issues a query to get the server version, and prints the result.
3) The document also discusses using cursors to execute statements and fetch results, handling errors, and retrieving results as tuples or dictionaries.
This document discusses connecting to and querying databases in Python. It outlines 7 steps to connect to a MySQL database: 1) start Python, 2) import database packages, 3) open a connection, 4) create a cursor, 5) execute queries, 6) extract data, and 7) clean up. It provides examples of connecting to MySQL and retrieving the first 3 rows from a student table.
The document discusses using Python's DB-API interface to write scripts that interact with MySQL databases. It describes installing the MySQLdb driver module, creating a connection to a MySQL server, executing queries using cursor objects, and retrieving and printing the results. A sample script is provided that connects to a test database, executes queries to create and populate a table with animal data, then selects and prints the data from the table.
ADO.NET is Microsoft's data access technology for .NET applications to connect to data sources. It uses a multilayered architecture centered around connections, commands, and dataset objects. Key differences from ADO include using a generic set of objects regardless of data source and a data provider model. ADO.NET supports features like interoperability, maintainability, typed programming, and performance through its disconnected data architecture.
This document discusses accessing and working with SQLite databases in Python. It covers the basics of connecting to a SQLite database, creating tables, inserting and updating data, and fetching data. The key steps are importing SQLite3, connecting to a database, using the connection to create a cursor to execute SQL statements like CREATE TABLE, INSERT, UPDATE, and SELECT. It also briefly mentions libraries for connecting to other SQL databases like PostgreSQL, MySQL, and Microsoft SQL Server. The goal is to teach the reader how to perform common CRUD operations with SQLite in Python.
The document discusses how to connect a Node.js application to a MySQL database. It covers setting up the environment, initializing a project, installing dependencies, creating a database, establishing a connection, handling environment variables, performing CRUD operations, handling errors, and calling stored procedures. Code examples are provided for each step to demonstrate how to connect Node.js to MySQL and execute queries to retrieve, add, update and delete data.
This document discusses MySQL, a popular database system used with PHP. It explains that MySQL stores data in tables with columns and rows, and that databases are useful for categorically storing information like employees, products, customers, and orders. It also discusses using PHP and MySQL together, performing queries on databases to retrieve specific recordsets, and how to connect to and manipulate a MySQL database using functions like mysqli_connect() in PHP.
Modulenotfounderror No module named 'mysql' in PythonHimani415946
mysql module not found is an error that occurs in python. It appears like ModuleNotError: No module named 'mysql.' This error occurs when you forget to install a module called mysql-connector-python in a preferable environment.
https://bit.ly/3RaJ0ro
This document provides an overview of Python database interfaces and APIs for connecting to relational and non-relational databases. It discusses popular database drivers like pyodbc, MySQLdb, and psycopg, which provide interfaces to SQL databases like SQL Server, MySQL, Oracle, and PostgreSQL. It also mentions ORM frameworks like Django that provide higher-level database access.
The document discusses database connectivity between a front-end interface and back-end database. It explains that the front-end is the user interface where data is entered, and the back-end is an invisible database that stores and provides data to the application. It then outlines the key components needed for connectivity - the JDBC API and driver to allow Java applications to interact with MySQL databases. The final sections describe classes used for connectivity like DriverManager, Connection, Statement, and ResultSet, and the typical steps to set up connectivity in a Java application.
This document discusses Python database programming. It introduces databases and how they store data in tables connected through columns. It discusses SQL for creating, accessing, and manipulating database data. It then discusses how Python supports various databases and database operations. It covers the Python DB-API for providing a standard interface for database programming. It provides examples of connecting to a database, executing queries, and retrieving and inserting data.
This document discusses connecting Python to databases. It outlines 4 steps: 1) importing database modules, 2) establishing a connection, 3) creating a cursor object, and 4) executing SQL queries. It provides code examples for connecting to MySQL and PostgreSQL databases, creating a cursor, and fetching data using methods like fetchall(), fetchmany(), and fetchone(). The document is an introduction to connecting Python applications to various database servers.
This document discusses how to install and use the mysql-connector-python package to connect to a MySQL database from Python. It provides instructions on installing Python and PIP if needed, then using PIP to install the mysql-connector-python package. It also describes verifying the installation by importing the mysql.connector module in a Python script without errors.
MySQL is an open-source relational database management system. It stores data in separate tables and uses SQL for querying and modifying the data. MySQL has a client-server architecture and supports different storage engines. Common tools for interacting with MySQL include the mysql command line client, mysqldump for backups, and graphical tools like phpMyAdmin.
What is the Philosophy of Statistics? (and how I was drawn to it)jemille6
What is the Philosophy of Statistics? (and how I was drawn to it)
Deborah G Mayo
At Dept of Philosophy, Virginia Tech
April 30, 2025
ABSTRACT: I give an introductory discussion of two key philosophical controversies in statistics in relation to today’s "replication crisis" in science: the role of probability, and the nature of evidence, in error-prone inference. I begin with a simple principle: We don’t have evidence for a claim C if little, if anything, has been done that would have found C false (or specifically flawed), even if it is. Along the way, I’ll sprinkle in some autobiographical reflections.
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18Celine George
In this slide, we’ll discuss on how to clean your contacts using the Deduplication Menu in Odoo 18. Maintaining a clean and organized contact database is essential for effective business operations.
Ad
More Related Content
Similar to Interface python with sql database.pdf-- (20)
This document discusses connecting to and querying databases in Python. It outlines 7 steps to connect to a MySQL database: 1) start Python, 2) import database packages, 3) open a connection, 4) create a cursor, 5) execute queries, 6) extract data, and 7) clean up. It provides examples of connecting to MySQL and retrieving the first 3 rows from a student table.
The document discusses using Python's DB-API interface to write scripts that interact with MySQL databases. It describes installing the MySQLdb driver module, creating a connection to a MySQL server, executing queries using cursor objects, and retrieving and printing the results. A sample script is provided that connects to a test database, executes queries to create and populate a table with animal data, then selects and prints the data from the table.
ADO.NET is Microsoft's data access technology for .NET applications to connect to data sources. It uses a multilayered architecture centered around connections, commands, and dataset objects. Key differences from ADO include using a generic set of objects regardless of data source and a data provider model. ADO.NET supports features like interoperability, maintainability, typed programming, and performance through its disconnected data architecture.
This document discusses accessing and working with SQLite databases in Python. It covers the basics of connecting to a SQLite database, creating tables, inserting and updating data, and fetching data. The key steps are importing SQLite3, connecting to a database, using the connection to create a cursor to execute SQL statements like CREATE TABLE, INSERT, UPDATE, and SELECT. It also briefly mentions libraries for connecting to other SQL databases like PostgreSQL, MySQL, and Microsoft SQL Server. The goal is to teach the reader how to perform common CRUD operations with SQLite in Python.
The document discusses how to connect a Node.js application to a MySQL database. It covers setting up the environment, initializing a project, installing dependencies, creating a database, establishing a connection, handling environment variables, performing CRUD operations, handling errors, and calling stored procedures. Code examples are provided for each step to demonstrate how to connect Node.js to MySQL and execute queries to retrieve, add, update and delete data.
This document discusses MySQL, a popular database system used with PHP. It explains that MySQL stores data in tables with columns and rows, and that databases are useful for categorically storing information like employees, products, customers, and orders. It also discusses using PHP and MySQL together, performing queries on databases to retrieve specific recordsets, and how to connect to and manipulate a MySQL database using functions like mysqli_connect() in PHP.
Modulenotfounderror No module named 'mysql' in PythonHimani415946
mysql module not found is an error that occurs in python. It appears like ModuleNotError: No module named 'mysql.' This error occurs when you forget to install a module called mysql-connector-python in a preferable environment.
https://bit.ly/3RaJ0ro
This document provides an overview of Python database interfaces and APIs for connecting to relational and non-relational databases. It discusses popular database drivers like pyodbc, MySQLdb, and psycopg, which provide interfaces to SQL databases like SQL Server, MySQL, Oracle, and PostgreSQL. It also mentions ORM frameworks like Django that provide higher-level database access.
The document discusses database connectivity between a front-end interface and back-end database. It explains that the front-end is the user interface where data is entered, and the back-end is an invisible database that stores and provides data to the application. It then outlines the key components needed for connectivity - the JDBC API and driver to allow Java applications to interact with MySQL databases. The final sections describe classes used for connectivity like DriverManager, Connection, Statement, and ResultSet, and the typical steps to set up connectivity in a Java application.
This document discusses Python database programming. It introduces databases and how they store data in tables connected through columns. It discusses SQL for creating, accessing, and manipulating database data. It then discusses how Python supports various databases and database operations. It covers the Python DB-API for providing a standard interface for database programming. It provides examples of connecting to a database, executing queries, and retrieving and inserting data.
This document discusses connecting Python to databases. It outlines 4 steps: 1) importing database modules, 2) establishing a connection, 3) creating a cursor object, and 4) executing SQL queries. It provides code examples for connecting to MySQL and PostgreSQL databases, creating a cursor, and fetching data using methods like fetchall(), fetchmany(), and fetchone(). The document is an introduction to connecting Python applications to various database servers.
This document discusses how to install and use the mysql-connector-python package to connect to a MySQL database from Python. It provides instructions on installing Python and PIP if needed, then using PIP to install the mysql-connector-python package. It also describes verifying the installation by importing the mysql.connector module in a Python script without errors.
MySQL is an open-source relational database management system. It stores data in separate tables and uses SQL for querying and modifying the data. MySQL has a client-server architecture and supports different storage engines. Common tools for interacting with MySQL include the mysql command line client, mysqldump for backups, and graphical tools like phpMyAdmin.
What is the Philosophy of Statistics? (and how I was drawn to it)jemille6
What is the Philosophy of Statistics? (and how I was drawn to it)
Deborah G Mayo
At Dept of Philosophy, Virginia Tech
April 30, 2025
ABSTRACT: I give an introductory discussion of two key philosophical controversies in statistics in relation to today’s "replication crisis" in science: the role of probability, and the nature of evidence, in error-prone inference. I begin with a simple principle: We don’t have evidence for a claim C if little, if anything, has been done that would have found C false (or specifically flawed), even if it is. Along the way, I’ll sprinkle in some autobiographical reflections.
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18Celine George
In this slide, we’ll discuss on how to clean your contacts using the Deduplication Menu in Odoo 18. Maintaining a clean and organized contact database is essential for effective business operations.
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabanifruinkamel7m
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptxArshad Shaikh
Insects have a segmented body plan, typically divided into three main parts: the head, thorax, and abdomen. The head contains sensory organs and mouthparts, the thorax bears wings and legs, and the abdomen houses digestive and reproductive organs. This segmentation allows for specialized functions and efficient body organization.
The role of wall art in interior designingmeghaark2110
Wall patterns are designs or motifs applied directly to the wall using paint, wallpaper, or decals. These patterns can be geometric, floral, abstract, or textured, and they add depth, rhythm, and visual interest to a space.
Wall art and wall patterns are not merely decorative elements, but powerful tools in shaping the identity, mood, and functionality of interior spaces. They serve as visual expressions of personality, culture, and creativity, transforming blank and lifeless walls into vibrant storytelling surfaces. Wall art, whether abstract, realistic, or symbolic, adds emotional depth and aesthetic richness to a room, while wall patterns contribute to structure, rhythm, and continuity in design. Together, they enhance the visual experience, making spaces feel more complete, welcoming, and engaging. In modern interior design, the thoughtful integration of wall art and patterns plays a crucial role in creating environments that are not only beautiful but also meaningful and memorable. As lifestyles evolve, so too does the art of wall decor—encouraging innovation, sustainability, and personalized expression within our living and working spaces.
Ajanta Paintings: Study as a Source of HistoryVirag Sontakke
This Presentation is prepared for Graduate Students. A presentation that provides basic information about the topic. Students should seek further information from the recommended books and articles. This presentation is only for students and purely for academic purposes. I took/copied the pictures/maps included in the presentation are from the internet. The presenter is thankful to them and herewith courtesy is given to all. This presentation is only for academic purposes.
This slide is an exercise for the inquisitive students preparing for the competitive examinations of the undergraduate and postgraduate students. An attempt is being made to present the slide keeping in mind the New Education Policy (NEP). An attempt has been made to give the references of the facts at the end of the slide. If new facts are discovered in the near future, this slide will be revised.
This presentation is related to the brief History of Kashmir (Part-I) with special reference to Karkota Dynasty. In the seventh century a person named Durlabhvardhan founded the Karkot dynasty in Kashmir. He was a functionary of Baladitya, the last king of the Gonanda dynasty. This dynasty ruled Kashmir before the Karkot dynasty. He was a powerful king. Huansang tells us that in his time Taxila, Singhpur, Ursha, Punch and Rajputana were parts of the Kashmir state.
Ancient Stone Sculptures of India: As a Source of Indian HistoryVirag Sontakke
This Presentation is prepared for Graduate Students. A presentation that provides basic information about the topic. Students should seek further information from the recommended books and articles. This presentation is only for students and purely for academic purposes. I took/copied the pictures/maps included in the presentation are from the internet. The presenter is thankful to them and herewith courtesy is given to all. This presentation is only for academic purposes.
Learn about the APGAR SCORE , a simple yet effective method to evaluate a newborn's physical condition immediately after birth ....this presentation covers .....
what is apgar score ?
Components of apgar score.
Scoring system
Indications of apgar score........
1. Chapter 11 :
Informatics
Practices
Class XII ( As per
CBSE Board)
Interface python
with SQL
Database And
SQL commands
Visit : python.mykvs.in for regular updates
New
Syllabus
2019-20
2. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
A database is nothing but an organized collection of data. Data is organized into rows, columns and
tables and it is indexed to make it easier to find relevant information. All companies whether large or
small use databases. So it become necessary to develop project/software using any programming
language like python in such a manner which can interface with such databases which support
SQL.Generalised form of Interface of python with SQL Database can be understood with the help of
this diagram.
Form/any user interface designed in any programming language is Front End where as data given
by database as response is known as Back-End database.
SQL is just a query language, it is not a database. To perform SQL queries, we need to install any
database for example Oracle, MySQL, MongoDB, PostGres SQL, SQL Server, DB2 etc.
Using SQL in any of the dbms ,databases and table can be created and data can be accessed,
updated and maintained. The Python standard for database interfaces is the Python DB-API. Python
Database API supports a wide range of database servers, like msql , mysql, postgressql, Informix,
oracle, Sybase etc.
3. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
Why choose Python for database programming
Following are the reason to choose python for database
programming
• Programming more efficient and faster compared to other
languages.
• Portability of python programs.
• Support platform independent program development.
• Python supports SQL cursors.
• Python itself take care of open and close of connections.
• Python supports relational database systems.
• Porting of data from one dbms to other is easily possible as it
support large range of APIs for various databases.
4. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
SQL Connectors
We must download a separate DB API module for each
database we need to access. Suppose we need to access an
Oracle database as well as a MySQL database, we must
download both the Oracle and the MySQL database modules .
The DB API provides a minimal standard for working with
databases using Python structures and syntax wherever
possible.
This API includes the following −
● Importing the API module.
● Acquiring a connection with the database.
● Issuing SQL statements and stored procedures.
● Closing the connection
5. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
Here we are using mysql as back end database because of it is open
source,free and portable and widely used. Any one of mysql-
connector or MySQLdb can be used for database programming.
1. mysql-connector
MySQL-Connector enables Python programs to access MySQL
databases, using an API that is compliant with the Python Database
API Specification v2.0 (PEP 249). It is written in pure Python and does
not have any dependencies except for the Python Standard Library.
Steps to use mysql-connector
1. Download Mysql API ,exe file and install it.(click here to download)
2. Install Mysql-Python Connector (Open command prompt and
execute command) >pip install mysql-connector
3. Now connect Mysql server using python
4. Write python statement in python shell import mysql.connector
If no error message is shown means mysql connector is properly
installed
6. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
2. MySQLdb
MySQLdb is an interface for connecting to a MySQL database server
from Python. It implements the Python Database API v2.0 and is built
on top of the MySQL C API.
Steps to use mysqlclient
1. First Upgrade pip command through > python –m pip install –
upgrade pip
2. Install mysqlclient through pip install mysqlclient
3. After successful installation check through import mysqldb
4. If it is installed no error will be displayed otherwise error message will be
displayed
To install MySQLdb module, use the following command −
For Ubuntu, use the following command -
$ sudo apt-get install python-pip python-dev libmysqlclient-dev
For Fedora, use the following command -
$ sudo dnf install python python-devel mysql-devel redhat-rpm-config gc c
For Python command prompt, use the following command -
pip install MySQL-python
Note − Make sure you have root privilege to install above module
7. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
Establish connection
For database interface/database programming ,connection must be
established.Before establishing connection there must be mysql installed on
the system and a database and table is already created.In following way we
can establish a connection with mysql database through mysql.connector.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root“,database
=“school”)
print(mydb)
Alternatively we can write the following statement if we are using mysqldb
import MySQLdb
mydb = MySQLdb.connect("localhost",“root",“root",“school" )
print(mydb)
In both way we are specifying host,user,password and database name as
arguments.database is optional argument if we want to create database
through programming later on.
After successful execution of above statements in python following out will
be displayed
<mysql.connector.connection.MySQLConnection object at 0x022624F0>
Otherwise an error message will be shown.
8. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
Cursor object :
The MySQLCursor class instantiates objects that can execute operations
such as SQL statements. Cursor objects interact with the MySQL server
using a MySQLConnection object.
How to create cursor object and use it
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root")
mycursor=mydb.cursor()
mycursor.execute("create database if not exists school")
mycursor.execute("show databases")
for x in mycursor:
print(x)
Through line 4 we are creating a database named school if it is already not
created with the help of cursor object.
Line 5 executes the sql query show databases and store result in mycursor
as collection ,whose values are being fetched in x variable one by one.
On execution of above program school database is created and a list of
available databases is shown.
9. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
How to create table at run time
Table creation is very easy ,if we are already well versed in sql table creation
then we have to just pass the create table query in execute() method of
cursor object. But before table creation we must open the database.Here we
are opening database school(through connect() method) before student table
creation.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root"
,database="school")
mycursor=mydb.cursor()
mycursor.execute("create table student(rollno int(3) primary key,name
varchar(20),age int(2))")
On successful execution of above program a table named student with three
fields rollno,name,age will be created in school database.
We can check student table in mysql shell also,if required.
10. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
How to change table structure/(add,edit,remove colum of a table) at run time
To modify the structure of the table we just have to use alter table
query.Below program will add a column mark in the student table.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root"
,database="school")
mycursor=mydb.cursor()
mycursor.execute("alter table student add (marks int(3))")
mycursor.execute("desc student")
for x in mycursor:
print(x)
Above program will add a column marks in the table student and will display
the structure of the table
11. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
How to search records of a table at run time
Below statement demonstrate the use of select query for searching specific
record from a table.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root"
,database="school")
mycursor=mydb.cursor()
nm=input("enter name")
mycursor.execute("select * from student where name='"+nm+"'")
for x in mycursor:
print (x)
Above statements will prompt a name from user,as user type the name ,that
name is searched into the table student with the help of select query .result
will be shown with the help of mycursor collection.
12. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
How to fetch all records of a table at run time
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root"
,database="school")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
myrecords=mycursor.fetchall()
for x in myrecords:
print (x)
MySQLCursor.fetchall() Method
The method fetches all (or all remaining) rows of a query result set and returns a
list of tuples. If no more rows are available, it returns an empty list.
13. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
How to fetch one record of a table at run time
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root"
,database="school")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
row=mycursor.fetchone()
while row is not None:
print(row)
row = mycursor.fetchone()
MySQLCursor.fetchone() Method
This method retrieves the next row of a query result set and returns a single
sequence, or None if no more rows are available. By default, the returned tuple
consists of data returned by the MySQL server, converted to Python objects.
MySQLCursor.fetchmany() Method
rows = cursor.fetchmany(size=1)
This method fetches the next set of rows of a query result and returns a list
of tuples. If no more rows are available, it returns an empty list.
14. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
How to delete record of a table at run time
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root"
,database="school")
mycursor=mydb.cursor()
mycursor.execute("delete from student where rollno=1")
mydb.commit()
In above program delete query will delete a record with rollno=1.commit()
method is necessary to call for database transaction.
How to update record of a table at run time
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="root"
,database="school")
mycursor=mydb.cursor()
mycursor.execute("update student set marks=99 where rollno=2")
mydb.commit()
In above program update query update the marks with 99 of rollno=2
Students are advised to develop menu driven program using above concepts
for better understating of python mysql database interface.
15. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
Manage Database Transaction
Database transaction represents a single unit of work. Any operation
which modifies the state of the MySQL database is a transaction.
Python MySQL Connector provides the following method to manage
database transactions.
commit – MySQLConnection.commit() method sends a COMMIT
statement to the MySQL server, committing the current transaction.
rollback – MySQLConnection.rollback revert the changes made by
the current transaction.
AutoCommit – MySQLConnection.autocommit value can be assigned
as True or False to enable or disable the auto-commit feature of
MySQL. By default its value is False.
16. Interface python with SQL Database
Visit : python.mykvs.in for regular updates
Manage Database Transaction
try:
conn = mysql.connector.connect(host='localhost',
database='school',
user='root',
password='root')
conn.autocommit = false
cursor = conn.cursor()
sql_update_query = """Update student set marks = 95 where rollno = 2"""
cursor.execute(sql_update_query)
print ("Record Updated successfully ")
#Commit your changes
conn.commit()
except mysql.connector.Error as error :
print("Failed to update record to database rollback: {}".format(error))
#reverting changes because of exception
conn.rollback()
finally:
#closing database connection.
if(conn.is_connected()):
cursor.close()
conn.close()
print("connection is closed")
In above program if update query is successfully executed then commit() method will be executed
otherwise exception error part will be executed where revert of update query will be done due to
error.At finally we are closing cursor as well as connection.To rollback or commit we have to set
autocommit=false,just like conn.autocommit = false in above program otherwise rollback will not work
17. SQL Commands
Visit : python.mykvs.in for regular updates
Grouping Records in a Query
• Some time it is required to apply a Select query in a group of
records instead of whole table.
• We can group records by using GROUP BY <column> clause
with Select command. A group column is chosen which have
non-distinct (repeating) values like City, Job etc.
• Generally, the following Aggregate Functions [MIN(), MAX(),
SUM(), AVG(), COUNT()] etc. are applied on groups.
Name Purpose
SUM() Returns the sum of given column.
MIN() Returns the minimum value in the given column.
MAX() Returns the maximum value in the given column.
AVG() Returns the Average value of the given column.
COUNT() Returns the total number of values/ records as per given
column.
18. SQL Commands
Visit : python.mykvs.in for regular updates
Aggregate Functions & NULL
Consider a table Emp having following records as-
Null values are excluded while (avg)aggregate function is
used
SQL Queries
mysql> Select Sum(Sal) from EMP;
mysql> Select Min(Sal) from EMP;
mysql> Select Max(Sal) from EMP;
mysql> Select Count(Sal) from EMP;
mysql> Select Avg(Sal) from EMP;
mysql> Select Count(*) from EMP;
Emp
Code Name Sal
E1 Mohak NULL
E2 Anuj 4500
E3 Vijay NULL
E4 Vishal 3500
E5 Anil 4000
Result of query
12000
3500
4500
3
4000
5
19. SQL Commands
Visit : python.mykvs.in for regular updates
Aggregate Functions & Group
An Aggregate function may applied on a column with DISTINCT or ALL
keyword. If nothing is given ALL is assumed.
Using SUM (<Column>)
This function returns the sum of values in given column or expression.
mysql> Select Sum(Sal) from EMP;
mysql> Select Sum(DISTINCT Sal) from EMP;
mysql> Select Sum (Sal) from EMP where City=‘Jaipur’;
mysql> Select Sum (Sal) from EMP Group By City;
mysql> Select Job, Sum(Sal) from EMP Group By Job;
Using MIN (<column>)
This functions returns the Minimum value in the given column.
mysql> Select Min(Sal) from EMP;
mysql> Select Min(Sal) from EMP Group By City;
mysql> Select Job, Min(Sal) from EMP Group By Job;
20. SQL Commands
Visit : python.mykvs.in for regular updates
Aggregate Functions & Group
Using MAX (<Column>)
This function returns the Maximum value in given column.
Using AVG (<column>)
This functions returns the Average value in the given column.
mysql> Select AVG(Sal) from EMP;
mysql> Select AVG(Sal) from EMP Group By City;
Using COUNT (<*|column>)
This functions returns the number of rows in the given
column.
mysql> Select Max(Sal) from EMP;
mysql> Select Max(Sal) from EMP where City=‘Jaipur’;
mysql> Select Max(Sal) from EMP Group By City;
mysql> Select Count ( * ) from EMP;
mysql> Select Count(Sal) from EMP Group By City;
mysql> Select Count(*), Sum(Sal) from EMP Group By Job;
21. SQL Commands
Visit : python.mykvs.in for regular updates
Aggregate Functions & Conditions
You may use any condition on group, if required. HAVING
<condition> clause is used to apply a condition on a group.
mysql> Select Job,Sum(Pay) from EMP
Group By Job HAVING Sum(Pay)>=8000;
mysql> Select Job, Sum(Pay) from EMP
Group By Job HAVING Avg(Pay)>=7000;
mysql> Select Job, Sum(Pay) from EMP
Group By Job HAVING Count(*)>=5;
mysql> Select Job, Min(Pay),Max(Pay), Avg(Pay) from EMP Group
By Job HAVING Sum(Pay)>=8000;
mysql> Select Job, Sum(Pay) from EMP Where City=‘Jaipur’
Note :- Where clause works in respect of whole table but Having works
on Group only. If Where and Having both are used then Where will be
executed first.
22. SQL Commands
Visit : python.mykvs.in for regular updates
Ordering Query Result – ORDER BY Clause
A query result can be orders in ascending (A-Z) or
descending (Z-A)
order as per any column. Default is Ascending order.
mysql> SELECT * FROM Student ORDER BY City;
To get descending order use DESC key word.
mysql> SELECT * FROM Student ORDER BY City
DESC;
mysql> SELECT Name, Fname, City FROM Student
Where Name LIKE ‘R%’ ORDER BY Class;