Python Tutorial ( PDFDrive )
• Issuing SQL statements and stored procedures.• Closing the connectionWe would learn all the concepts using MySQL, so let's talk about MySQLdb module only.What is MySQLdb? MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the PythonDatabase API v2.0 and is built on top of the MySQL C API.How do I install the MySQLdb? Before proceeding, you make sure you have MySQLdb installed on your machine. Just type the following in yourPython script and execute it:#!/usr/bin/pythonimport MySQLdbIf it produces the following result, then it means MySQLdb module is not installed:Traceback (most recent call last):File "test.py", line 3, in <module>import MySQLdbImportError: No module named MySQLdbTo install MySQLdb module, download it from MySQLdb Download page and proceed as follows:$ gunzip MySQL-python-1.2.2.tar.gz$ tar -xvf MySQL-python-1.2.2.tar$ cd MySQL-python-1.2.2$ python setup.py build$ python setup.py installNote: Make sure you have root privilege to install above module.Database Connection: Before connecting to a MySQL database, make sure of the followings:• You have created a database TESTDB.• You have created a table EMPLOYEE in TESTDB.• This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.• User ID "testuser" and password "test123" are set to access TESTDB.• Python module MySQLdb is installed properly on your machine.• You have gone through MySQL tutorial to understand MySQL Basics.TUTORIALS POINT Simply Easy Learning
EXAMPLE: Following is the example of connecting with MySQL database "TESTDB":#!/usr/bin/pythonimport MySQLdb# Open database connectiondb = MySQLdb.connect("localhost","testuser","test123","TESTDB" )# prepare a cursor object using cursor() methodcursor = db.cursor()# execute SQL query using execute() method.cursor.execute("SELECT VERSION()")# Fetch a single row using fetchone() method.data = cursor.fetchone()print "Database version : %s " % data# disconnect from serverdb.close()While running this script, it is producing the following result at my Linux machine:Database version : 5.0.45If a connection is established with the datasource, then a Connection Object is returned and saved intodb forfurther use, otherwise db is set to None. Next, db object is used to create a cursor object, which in turn is used toexecute SQL queries. Finally, before coming out, it ensures that database connection is closed and resources arereleased.Creating Database Table: Once a database connection is established, we are ready to create tables or records into the database tablesusing execute method of the created cursor.EXAMPLE: First, let's create Database table EMPLOYEE:#!/usr/bin/pythonimport MySQLdb# Open database connectiondb = MySQLdb.connect("localhost","testuser","test123","TESTDB" )# prepare a cursor object using cursor() methodcursor = db.cursor()# Drop table if it already exist using execute() method.cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")# Create table as per requirementsql = """CREATE TABLE EMPLOYEE (FIRST_NAME CHAR(20) NOT NULL,TUTORIALS POINT Simply Easy Learning
- Page 289 and 290: Return Value This method does not
- Page 291 and 292: # stat informationstatinfo = os.sta
- Page 293 and 294: Description The method tcgetpgrp()
- Page 295 and 296: os.tempnam(dir, prefix)Parameters
- Page 297 and 298: Description The method ttyname() re
- Page 299 and 300: Return Value This method does not
- Page 301 and 302: Return Value This method returns t
- Page 303 and 304: KeyErrorNameErrorUnboundLocalErrorE
- Page 305 and 306: ......................else:If there
- Page 307 and 308: print "Error: can\'t find file or r
- Page 309 and 310: self.args = argSo once you defined
- Page 311 and 312: 'Optional class documentation strin
- Page 313 and 314: For the above class let's try to ac
- Page 315 and 316: print 'Calling child method'c = Chi
- Page 317 and 318: Data Hiding: An object's attribute
- Page 319 and 320: groups()This method returns all mat
- Page 321 and 322: SYNTAX: re.sub(pattern, repl, strin
- Page 323 and 324: \s Matches whitespace. Equivalent t
- Page 325 and 326: Backreferences: This matches a prev
- Page 327 and 328: CHAPTER20Python CGI ProgrammingWhat
- Page 329 and 330: If you click hello.py, then this pr
- Page 331 and 332: Simple URL Example : Get Metho
- Page 333 and 334: </form>The result of this code is t
- Page 335 and 336: text_content = form.getvalue('textc
- Page 337 and 338: Here is an example of how to retrie
- Page 339: CHAPTER21Python Database AccessThe
- Page 343 and 344: ('Mac', 'Mohan', 20, 'M', 2000)try:
- Page 345 and 346: DELETE Operation: DELETE operation
- Page 347 and 348: ProgrammingErrorSubclass of Databas
- Page 349 and 350: The socket Module: To create a so
- Page 351 and 352: Protocol Common function Port No Py
- Page 353 and 354: Subject: SMTP e-mail testThis is a
- Page 355 and 356: try:smtpObj = smtplib.SMTP('localho
- Page 357 and 358: count = 0while count < 5:time.sleep
- Page 359 and 360: Synchronizing Threads: The threadi
- Page 361 and 362: thread = myThread(threadID, tName,
- Page 363 and 364: <stars>10</stars><description>Talk
- Page 365 and 366: print "Rating:", self.ratingelif se
- Page 367 and 368: Format: DVDRating: PGDescription: T
- Page 369 and 370: Tkinter Widgets Tkinter provides v
- Page 371 and 372: fgfontheighthighlightcolorimagejust
- Page 373 and 374: WidthXscrollincrementXscrollcommand
- Page 375 and 376: pattern when it is over the checkbu
- Page 377 and 378: The Entry widget is used to accept
- Page 379 and 380: E1 = Entry(top, bd =5)E1.pack(side
- Page 381 and 382: Optionanchorbgbitmapbdcursorfontfgh
- Page 383 and 384: selectmodeDetermines how many items
- Page 385 and 386: Syntax: Here is the simple syntax t
- Page 387 and 388: Menu The goal of this widget is to
- Page 389 and 390: filemenu.add_command(label="Exit",
EXAMPLE:
Following is the example of connecting with MySQL database "TESTDB":
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print "Database version : %s " % data
# disconnect from server
db.close()
While running this script, it is producing the following result at my Linux machine:
Database version : 5.0.45
If a connection is established with the datasource, then a Connection Object is returned and saved intodb for
further use, otherwise db is set to None. Next, db object is used to create a cursor object, which in turn is used to
execute SQL queries. Finally, before coming out, it ensures that database connection is closed and resources are
released.
Creating Database Table:
Once a database connection is established, we are ready to create tables or records into the database tables
using execute method of the created cursor.
EXAMPLE:
First, let's create Database table EMPLOYEE:
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
TUTORIALS POINT
Simply Easy Learning