Database Programming in Python - Python Connect To Database
Database Programming in Python - Python Connect To Database
13
Minutes Remaining
share
tweet
share
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 1/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
TABLE OF CONTENTS
Connection Objects
Cursor Objects
Cursor Objects
Cursor Attributes
Cursor Methods
Database Connection
INSERT Operation
READ Operation
UPDATE Operation
DELETE Operation
COMMIT Operation
ROLLBACK Operation
Connection Objects
Connection objects in DB-API of Python create a connection with the
database which is further used for different transactions. These
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 3/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
Cursor Objects
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 4/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
The cursor is one of the powerful features of SQL. These are objects
that are responsible for submitting various SQL statements to a
database server. There are several cursor classes in
MySQLdb.cursors:
cursor.close()
Cursor Objects
These objects represent a database cursor, which is used to manage
the context of a fetch operation. Cursors created from the same
connection are not isolated, i.e., any changes done to the database
by a cursor are immediately visible by the other cursors. Cursors
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 5/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
Cursor Attributes
Cursor Objects should respond to the following methods and
attributes.
name
type_code
display_size
internal_size
precision
scale
null_ok
The first two items (name and type_code) are mandatory, the other
five are optional and are set to None if no meaningful values can be
provided. This attribute will be None for operations that do not
return rows or if the cursor has not had an operation invoked via the
.execute*() method yet.
Cursor Methods
This method is optional since not all databases provide stored
procedures.
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 6/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
.close(): Close the cursor now. The cursor will be unusable from this
point forward; an Error (or subclass) exception will be raised if any
operation is attempted with the cursor.
You can use this method for an operation that produces one or
more result sets that constitutes undefined behavior, and the
implementation is permitted (but not required) to raise an exception
when it detects that a result set has been created by an invocation of
the operation.
.nextset(): This method will make the cursor skip to the next
available set, discarding any remaining rows from the current set. If
there are no more sets, the method returns None. Otherwise, it
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 8/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
import MySQLdb
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 9/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
Database Connection
The first step in using a database in a program is to establish a
database connection.
import MySQLdb
db =
MySQLdb.connect("localhost","testuser","test123","TEST
DB" )
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
db.close()
import MySQLdb
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 10/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
db =
MySQLdb.connect("localhost","testuser","test123","TEST
DB" )
cursor = db.cursor()
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
db.close()
INSERT Operation
It is required when you want to create your records into a database
table. The following example, executes SQL INSERT statement to
create a record into EMPLOYEE table:
import MySQLdb
db =
MySQLdb.connect("localhost","testuser","test123","TEST
DB" )
cursor = db.cursor()
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 11/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
READ Operation
READ operation on any database means to fetch some useful
information from the database. Once your database connection is
established, you are ready to make a query into this database. You
can use either fetchone() method to fetch a single record or
fetchall() method to fetch multiple values from a database table.
The following code queries all the records from EMPLOYEE table
having salary more than 1000:
import MySQLdb
db =
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 12/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
MySQLdb.connect("localhost","testuser","test123","TEST
DB" )
cursor = db.cursor()
try:
cursor.execute(sql)
results = cursor.fetchall()
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print
"fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
except:
db.close()
UPDATE Operation
UPDATE operation on any database means to update one or more
records, which are already available in the database. The following
code updates all the records having SEX as ‘M’ by increasing AGE by
one year.
import MySQLdb
db =
MySQLdb.connect("localhost","testuser","test123","TEST
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 13/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
DB" )
cursor = db.cursor()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
DELETE Operation
It is required when you want to delete some records from your
database. Following is the code to delete all the records from
EMPLOYEE where AGE is more than 20:
import MySQLdb
db =
MySQLdb.connect("localhost","testuser","test123","TEST
DB" )
cursor = db.cursor()
try:
cursor.execute(sql)
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 14/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
db.commit()
except:
db.rollback()
db.close()
COMMIT Operation
Commit is the operation, which gives a green signal to a database to
finalize the changes, and after this operation, no change can be
reverted. The following code is used to perform commit operation:
db.commit()
ROLLBACK Operation
If you are not satisfied with one or more of the changes and you
want to revert those changes completely, then you can use the
rollback() method. The following code will perform the rollback
operation.
db.rollback()
db.close()
Read More
Read More
0 comments
Top rated
comments first
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 16/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
Comment as a guest:
Name
Website
Submit comment
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 17/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
register
CATEGORIES
Coding Trivia
RECENT POSTS
TAGS CLOUD
Search Here...
ARCHIVES
CONTACT SOCIAL
Home
Blog
CodingHero Reviews &
Testimonials
Privacy policy
Terms and Conditions
Do you want your kid to showcase her / his creating abilities by using the latest
emerging technologies? We at Coding Hero provide a favorable environment
and opportunities to explore various platforms such as game development,
mobile app development. Our online coding, design, chess and math courses
are designed to suit kids' learning pace.
We not only teach kids the basics of coding, maths and design, but also make
them proficient in logical thinking that enable kids to create wonderful games,
animations, and apps.
About CodingHero
At CodingHero, the kids start learning through our online classes for coding,
design, chess and maths. Our online courses introduce the kids from 5 years
of age to the whole new exciting world of coding by learning web
development, game development, chess strategies and moves, maths
concepts, and mobile app development and that too from the comfort of your
home.
Kids begin to code using block-based visual language, which helps them
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 20/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
Game Development
Animations
Web Development
Python
Artificial Intelligence
Machine Learning
Data Science
Maths
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 22/23
10/8/21, 5:48 PM Database Programming in Python | Python Connect to Database
https://codinghero.ai/database-programming-in-python-tutorial-for-beginners/ 23/23