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.
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...Arshad Shaikh
Dictyoptera is an order of insects that includes cockroaches and praying mantises. These insects are characterized by their flat, oval-shaped bodies and unique features such as modified forelegs in mantises for predation. They inhabit diverse environments worldwide.
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.
"Dictyoptera: The Order of Cockroaches and Mantises" Or, more specifically: ...Arshad Shaikh
Dictyoptera is an order of insects that includes cockroaches and praying mantises. These insects are characterized by their flat, oval-shaped bodies and unique features such as modified forelegs in mantises for predation. They inhabit diverse environments worldwide.
IDSP is a disease surveillance program in India that aims to strengthen/maintain decentralized laboratory-based IT enabled disease surveillance systems for epidemic prone diseases to monitor disease trends, and to detect and respond to outbreaks in the early phases swiftly.....
Prottutponnomotittwa: A Quiz That Echoed the Pulse of Bengal
On the 31st of May, 2025, PRAGYA – The Official Quiz Club of UEM Kolkata – did not merely organize another quiz. It hosted an ode to Bengal — its people, its quirks, its politics, its art, its rebellion, its heritage. Titled Prottutponnomotittwa, the quiz stood as a metaphor for what Bengal truly is: sharp, intuitive, spontaneous, reflective. A cultural cosmos that thrives on instinct, memory, and emotion.
From the very first slide, it became clear — this wasn’t a quiz made to showcase difficulty or elitism. It was crafted with love — love for Bangla, for its past, present, and its ever-persistent contradictions.
The diversity of the answer list tells the real story of the quiz. The curation was not random. Each answer was a string on a veena of cultural resonance.
In the “Cultural Pairings” round, Anusheh Anadil and Arnob were placed not just as musicians, but as voices of a modern, cross-border Bangla. Their works, which blend baul, jazz, and urban folk, show how Bengal exists simultaneously in Dhaka and Shantiniketan.
The inclusion of Ritwik Chakraborty and Srijit Mukherjee (as a songwriter) showed how the quiz masters understood evolution. Bangla cinema isn’t frozen in the Ray-Ghatak past. It lives, argues, breaks molds — just like these men do.
From Kalyani Black Label to Radhunipagol Chal, consumer culture too had its place. One is liquid courage, the other culinary madness — both deeply Bengali.
The heart truly swelled when the answers touched upon Baidyanath Bhattacharya and Chandril. Both satirists, both sharp, both essential. It was not just about naming them — it was about understanding what different types of literature means in a Bengali context.
Titumir — the play about a peasant rebel who built his own bamboo fort and dared to challenge the British.
Krishnananda Agamvagisha — the mystical Tantric who shaped how we understand esoteric Bengali spiritualism.
Subhas Chandra Bose — the eternal enigma, the braveheart whose shadow looms large over Bengal’s political psyche.
Probashe Ghorkonna — a story lived by many Bengalis. The medinipur daughter, who made a wholesome family, not only in bengal, but across the borders. This answer wasn’t just information. It was emotion.
By the end, what lingered was not the scoreboard. It was a feeling.
The feeling of sitting in a room where Chalchitro meets Chabiwala, where Jamai Shosthi shares the stage with Gayatri Spivak, where Bhupen Hazarika sings with Hemanga Biswas, and where Alimuddin Road and Webskitters occupy the same mental map.
You don’t just remember questions from this quiz.
You remember how it made you feel.
You remember smiling at Keet Keet, nodding at Prabuddha Dasgupta, getting goosebumps at the mention of Bose, and tearing up quietly when someone got Radhunipagol Chal right.
This wasn’t a quiz.
This was an emotional ride of Bangaliyana.
This was — and will remain — Prottutponnomotittwa.
How to Manage Orders in Odoo 18 Lunch - Odoo SlidesCeline George
The Lunch module in Odoo 18 helps users place their food orders, making meal management seamless and efficient. It allows employees to browse available options, place orders, and track their meals effortlessly.
Here is the current update:
CURRENT CASE COUNT: 897
- Texas: 742 (+14) (55% of cases are in Gaines County). Includes additional numbers from El Paso.
- New Mexico: 79 (+1) (83% of cases are from Lea County)
- Oklahoma: 17
- Kansas: 59 (+3) (38.89% of the cases are from Gray County)
HOSPITALIZATIONS: 103
- Texas: 94 – This accounts for 13% of all cases in Texas.
- New Mexico: 7 – This accounts for 9.47% of all cases in New Mexico.
- Kansas: 3 – This accounts for 5.08% of all cases in Kansas.
DEATHS: 3
- Texas: 2 – This is 0.28% of all cases in Texas.
- New Mexico: 1 – This is 1.35% of all cases in New Mexico.
US NATIONAL CASE COUNT: 1,132 (confirmed and suspected)
INTERNATIONAL SPREAD
Mexico: 1,856(+103), 4 fatalities
- Chihuahua, Mexico: 1,740 (+83) cases, 3 fatalities, 4 currently hospitalized.
Canada: 2,791 (+273)
- Ontario, Canada: 1,938 (+143) cases. 158 (+29) hospitalizations
- Alberta, Canada: 679 (+119) cases. 4 currently hospitalized
"Orthoptera: Grasshoppers, Crickets, and Katydids pptxArshad Shaikh
Orthoptera is an order of insects that includes grasshoppers, crickets, and katydids. Characterized by their powerful hind legs, Orthoptera are known for their impressive jumping ability. With diverse species, they inhabit various environments, playing important roles in ecosystems as herbivores and prey. Their sounds, often produced through stridulation, are distinctive features of many species.
Coleoptera, commonly known as beetles, is the largest order of insects, comprising approximately 400,000 described species. Beetles can be found in almost every habitat on Earth, exhibiting a wide range of morphological, behavioral, and ecological diversity. They have a hardened exoskeleton, with the forewings modified into elytra that protect the hind wings. Beetles play important roles in ecosystems as decomposers, pollinators, and food sources for other animals, while some species are considered pests in agriculture and forestry.
Order: Odonata Isoptera and Thysanoptera.pptxArshad Shaikh
*Odonata*: Odonata is an order of insects that includes dragonflies and damselflies. Characterized by their large, compound eyes and agile flight, they are predators that feed on other insects, playing a crucial role in maintaining ecological balance.
*Isoptera*: Isoptera is an order of social insects commonly known as termites. These eusocial creatures live in colonies with complex social hierarchies and are known for their ability to decompose wood and other cellulose-based materials, playing a significant role in ecosystem nutrient cycling.
*Thysanoptera*: Thysanoptera, or thrips, are tiny insects with fringed wings. Many species are pests that feed on plant sap, transmitting plant viruses and causing damage to crops and ornamental plants. Despite their small size, they have significant impacts on agriculture and horticulture.
♥☽✷♥
Make sure to catch our weekly updates. Updates are done Thursday to Fridays or its a holiday/event weekend.
Thanks again, Readers, Guest Students, and Loyalz/teams.
This profile is older. I started at the beginning of my HQ journey online. It was recommended by AI. AI was very selective but fits my ecourse style. I am media flexible depending on the course platform. More information below.
AI Overview:
“LDMMIA Reiki Yoga refers to a specific program of free online workshops focused on integrating Reiki energy healing techniques with yoga practices. These workshops are led by Leslie M. Moore, also known as LDMMIA, and are designed for all levels, from beginners to those seeking to review their practice. The sessions explore various themes like "Matrix," "Alice in Wonderland," and "Goddess," focusing on self-discovery, inner healing, and shifting personal realities.”
♥☽✷♥
“So Life Happens-Right? We travel on. Discovering, Exploring, and Learning...”
These Reiki Sessions are timeless and about Energy Healing / Energy Balancing.
A Shorter Summary below.
A 7th FREE WORKSHOP
REiki - Yoga
“Life Happens”
Intro Reflections
Thank you for attending our workshops. If you are new, do welcome. We have been building a base for advanced topics. Also, this info can be fused with any Japanese (JP) Healing, Wellness Plans / Other Reiki /and Yoga practices.
Power Awareness,
Our Defense.
Situations like Destiny Swapping even Evil Eyes are “stealing realities”. It’s causing your hard earned luck to switch out. Either way, it’s cancelling your reality all together. This maybe common recently over the last decade? I noticed it’s a sly easy move to make. Then, we are left wounded, suffering, accepting endless bad luck. It’s time to Power Up. This can be (very) private and quiet. However; building resources/EDU/self care for empowering is your business/your right. It’s a new found power we all can use for healing.
Stressin out-II
“Baby, Calm down, Calm Down.” - Song by Rema, Selena Gomez (Video Premiered Sep 7, 2022)
Within Virtual Work and VR Sims (Secondlife Metaverse) I love catching “Calm Down” On the radio streams. I love Selena first. Second, It’s such a catchy song with an island feel. This blends with both VR and working remotely.
Its also, a good affirmation or mantra to *Calm down* lol.
Something we reviewed in earlier Workshops.
I rarely mention love and relations but theres one caution.
When we date, almost marry an energy drainer/vampire partner; We enter doorways of no return. That person can psychic drain U during/after the relationship. They can also unleash their demons. Their dark energies (chi) can attach itself to you. It’s SYFI but common. Also, involving again, energy awareness. We are suppose to keep our love life sacred. But, Trust accidents do happen. The Energies can linger on. Also, Reiki can heal any breakup damage...
(See Pres for more info. Thx)
How to Setup Lunch in Odoo 18 - Odoo guidesCeline George
In Odoo 18, the Lunch application allows users a convenient way to order food and pay for their meal directly from the database. Lunch in Odoo 18 is a handy application designed to streamline and manage employee lunch orders within a company.
Types of Actions in Odoo 18 - Odoo SlidesCeline George
In Odoo, actions define the system's response to user interactions, like logging in or clicking buttons. They can be stored in the database or returned as dictionaries in methods. Odoo offers various action types for different purposes.
Christian education is an important element in forming moral values, ethical Behaviour and
promoting social unity, especially in diverse nations like in the Caribbean. This study examined
the impact of Christian education on the moral growth in the Caribbean, characterized by
significant Christian denomination, like the Orthodox, Catholic, Methodist, Lutheran and
Pentecostal. Acknowledging the historical and social intricacies in the Caribbean, this study
tends to understand the way in which Christian education mold ethical decision making, influence interpersonal relationships and promote communal values. These studies’ uses, qualitative and quantitative research method to conduct semi-structured interviews for twenty
(25) Church respondents which cut across different age groups and genders in the Caribbean. A
thematic analysis was utilized to identify recurring themes related to ethical Behaviour, communal values and moral development. The study analyses the three objectives of the study:
how Christian education Mold’s ethical Behaviour and enhance communal values, the role of
Christian educating in promoting ecumenism and the effect of Christian education on moral
development. Moreover, the findings show that Christian education serves as a fundamental role
for personal moral evaluation, instilling a well-structured moral value, promoting good
Behaviour and communal responsibility such as integrity, compassion, love and respect. However, the study also highlighted challenges including biases in Christian teachings, exclusivity and misconceptions about certain practices, which impede the actualization of
Pragya Champion's Chalice is the annual Intra Pragya General Quiz hosted by the club's outgoing President and Vice President. The prelims and finals are both given in the singular set.
How to Create a Stage or a Pipeline in Odoo 18 CRMCeline George
In Odoo, the CRM (Customer Relationship Management) module’s pipeline is a visual representation of a company's sales process that helps sales teams track and manage their interactions with potential customers.
SEM II 3202 STRUCTURAL MECHANICS, B ARCH, REGULATION 2021, ANNA UNIVERSITY, R...RVSPSOA
Principles of statics. Forces and their effects. Types of force systems. Resultant of concurrent and
parallel forces. Lami’s theorem. Principle of moments. Varignon’s theorem. Principle of equilibrium.
Types of supports and reactions-Bending moment and Shear forces-Determination of reactions for
simply supported beams. Relation between bending moment and shear force.
Properties of section – Centre of gravity, Moment of Inertia, Section modulus, Radius of gyration
for various structural shapes. Theorem of perpendicular axis. Theorem of parallel axis.
Elastic properties of solids. Concept of stress and strain. Deformation of axially loaded simple bars.
Types of stresses. Concept of axial and volumetric stresses and strains. Elastic constants. Elastic
Modulus. Shear Modulus. Bulk Modulus. Poisson’s ratio. Relation between elastic constants.
Principal stresses and strain. Numerical and Graphical method. Mohr’s diagram.
R.K. Bansal, ‘A Text book on Engineering Mechanics’, Lakshmi Publications, Delhi,2008.
R.K. Bansal, ‘A textbook on Strength of Materials’, Lakshmi Publications, Delhi 2010.
Paul W. McMullin, 'Jonathan S. Price, ‘Introduction to Structures’, Routledge, 2016.
P.C. Punmia, ‘Strength of Materials and Theory of Structures; Vol. I’, Lakshmi
Publications, Delhi 2018.
2. S. Ramamrutham, ‘Strength of Materials’, Dhanpatrai and Sons, Delhi, 2014.
3. W.A. Nash, ‘Strength of Materials’, Schaums Series, McGraw Hill Book Company,1989.
4. R.K. Rajput, ‘Strength of Materials’, S.K. Kataria and Sons, New Delhi , 2017.
The PDF titled "Critical Thinking and Bias" by Jibi Moses aims to equip a diverse audience from South Sudan with the knowledge and skills necessary to identify and challenge biases and stereotypes. It focuses on developing critical thinking abilities and promoting inclusive attitudes to foster a more cohesive and just society. It defines bias as a tendency or prejudice affecting perception and interactions, categorizing it into conscious and unconscious (implicit) biases. The content highlights the impact of societal and cultural conditioning on these biases, particularly within the South Sudanese context.
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;