0% found this document useful (0 votes)
7 views13 pages

PYTHON Unit 5

This document provides a comprehensive guide on connecting Python with SQL databases using the MySQL Connector module, including how to create tables and execute queries. It also covers reading .ini configuration files with the configparser module, threading in Python, and creating child processes using the fork() function. The document includes code examples and explanations for each topic, making it a useful resource for Python developers.

Uploaded by

Siddarth Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views13 pages

PYTHON Unit 5

This document provides a comprehensive guide on connecting Python with SQL databases using the MySQL Connector module, including how to create tables and execute queries. It also covers reading .ini configuration files with the configparser module, threading in Python, and creating child processes using the fork() function. The document includes code examples and explanations for each topic, making it a useful resource for Python developers.

Uploaded by

Siddarth Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

How to Connect Python with SQL Database?

Python is a high-level, general-purpose, and very popular programming language. Basically, it


was designed with an emphasis on code readability, and programmers can express their
concepts in fewer lines of code. We can also use Python with SQL. In this article, we will learn
how to connect SQL with Python using the ‘MySQL Connector Python module. The diagram
given below illustrates how a connection request is sent to MySQL connector Python, how it gets
accepted from the database and how the cursor is executed with result data.

Creating a table in MySQL


The CREATE TABLE statement is used to create tables in MYSQL database. Here, you need to specify the
name of the table and, definition (name and datatype) of each column.

Syntax
Following query creates a table named EMPLOYEE in MySQL with five columns namely, FIRST_NAME,
LAST_NAME, AGE, SEX and, INCOME.

mysql> CREATE TABLE EMPLOYEE(


FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT
);
Creating a table in MySQL using python
The method named execute() (invoked on the cursor object) accepts two variables −
 A String value representing the query to be executed.
 An optional args parameter which can be a tuple or, list or, dictionary, representing the
parameters of the query (values of the place holders).
It returns an integer value representing the number of rows effected by the query.
Once a database connection is established, you can create tables by passing the CREATE TABLE query to
the execute() method.
In short, to create a table using python 7minus;

 Import mysql.connector package.


 Create a connection object using the mysql.connector.connect() method, by passing the
user name, password, host (optional default: localhost) and, database (optional) as parameters
to it.
 Create a cursor object by invoking the cursor() method on the connection object created
above.
 Then, execute the CREATE TABLE statement by passing it as a parameter to
the execute() method.

Reading .ini Configuration Files


This article aims to read configuration files written in the common .ini configuration file format.
The configparser module can be used to read configuration files.

Code #1 : Configuration File


abc.ini

; Sample configuration file

[installation]

library = %(prefix)s/lib

include = %(prefix)s/include
bin = %(prefix)s/bin

prefix = /usr/local

# Setting related to debug configuration

[debug]

pid-file = /tmp/spam.pid

show_warnings = False

log_errors = true

[server]

nworkers: 32

port: 8080

root = /www/root

signature:

Code #2 : Reading the file and extracting values.


from configparser import ConfigParser

configur = ConfigParser()

print (configur.read('config.ini'))

print ("Sections : ", configur.sections())

print ("Installation Library : ", configur.get('installation','library'))

print ("Log Errors debugged ? : ", configur.getboolean('debug','log_errors'))

print ("Port Server : ", configur.getint('server','port'))

print ("Worker Server : ", configur.getint('server','nworkers'))

Output :
['config.ini']
Sections : ['installation', 'debug', 'server']
Installation Library : '/usr/local/lib'
Log Errors debugged ? : True
Port Server : 8080
Worker Server : 32

Code #3

configur.set('server','port','9000')

configur.set('debug','log_errors','False')

import sys

configur.write(sys.stdout)

Output :
[installation]
library = %(prefix)s/lib
include = %(prefix)s/include
bin = %(prefix)s/bin
prefix = /usr/local

[debug]
log_errors = False
show_warnings = False

[server]
port = 9000
nworkers = 32
pid-file = /tmp/spam.pid
root = /www/root

 Configuration files are well suited to specify configuration data to your program. Within
each config file, values are grouped into different sections (e.g., “installation”, “debug”
and “server”).
 Each section then has a specific value for various variables in that section. For the same
purpose, there are some prominent differences between a config file and using a
Python source file.
 First, the syntax is much more permissive and “sloppy.”

Programming using database connections:


Database Connection:
There are the following steps to connect a python application to our database.

1. Import mysql.connector module


2. Create the connection object.
3. Create the cursor object
4. Execute the query

Creating the connection


To create a connection between the MySQL database and the python application, the connect() method of
mysql.connector module is used.

Pass the database details like HostName, username, and the database password in the method call. The
method returns the connection object.

The syntax to use the connect() is given below.

1. Connection-Object= mysql.connector.connect(host = <host-


name> , user = <username> , passwd = <password> )

Consider the following example.

Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
5.
6. #printing the connection object
7. print(myconn)

Output:

<mysql.connector.connection.MySQLConnection object at 0x7fb142edd780>


Here, we must notice that we can specify the database name in the connect() method if we want to connect
to a specific database.

Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database = "mydb")
4.
5. #printing the connection object
6. print(myconn)

Output:

<mysql.connector.connection.MySQLConnection object at 0x7ff64aa3d7b8>

Creating a cursor object


The cursor object can be defined as an abstraction specified in the Python DB-API 2.0. It facilitates us to have
multiple separate working environments through the same connection to the database. We can create the
cursor object by calling the 'cursor' function of the connection object. The cursor object is an important
aspect of executing queries to the databases.

The syntax to create the cursor object is given below.

1. <my_cur> = conn.cursor()
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database =
"mydb")
4.
5. #printing the connection object
6. print(myconn)
7.
8. #creating the cursor object
9. cur = myconn.cursor()
10.
11. print(cur)

Output:<mysql.connector.connection.MySQLConnection object at 0x7faa17a15748> MySQLCursor:


(Nothing executed yet)
An Intro to Threading in Python
A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest
unit of processing that can be performed in an OS (Operating System). In simple words, a thread
is a sequence of such instructions within a program that can be executed independently of other
code. For simplicity, you can assume that a thread is simply a subset of a process! A thread
contains all this information in a Thread Control Block (TCB):
 Thread Identifier: Unique id (TID) is assigned to every new thread
 Stack pointer: Points to the thread’s stack in the process. The stack contains the local
variables under the thread’s scope.
 Program counter: a register that stores the address of the instruction currently being
executed by a thread.
 Thread state: can be running, ready, waiting, starting, or done.
 Thread’s register set: registers assigned to thread for computations.
 Parent process Pointer: A pointer to the Process control block (PCB) of the process
that the thread lives on.

Multiple threads can exist within one process where:


 Each thread contains its own register set and local variables (stored in the stack).
 All threads of a process share global variables (stored in heap) and the program
code.
Consider the diagram below to understand how multiple threads exist in memory:
Multithreading is defined as the ability of a processor to execute multiple threads concurrently.
In a simple, single-core CPU, it is achieved using frequent switching between threads. This is
termed context switching. In context switching, the state of a thread is saved and the state of
another thread is loaded whenever any interrupt (due to I/O or manually set) takes place.
Context switching takes place so frequently that all the threads appear to be running parallelly
(this is termed multitasking).
Consider the diagram below in which a process contains two active threads:

Multithreading programming in Python


In Python, the threading module provides a very simple and intuitive API for spawning multiple
threads in a program. Let us try to understand multithreading code step-by-step.
Step 1: Import Module
First, import the threading module.
import threading

Step 2: Create a Thread


To create a new thread, we create an object of the Thread class. It takes the ‘target’ and ‘args’ as
the parameters. The target is the function to be executed by the thread whereas the args is the
arguments to be passed to the target function.
t1 = threading.Thread(target, args)
t2 = threading.Thread(target, args)

Step 3: Start a Thread


To start a thread, we use the start() method of the Thread class.
t1.start()
t2.start()

Step 4: End the thread Execution


Once the threads start, the current program (you can think of it like a main thread) also keeps on
executing. In order to stop the execution of the current program until a thread is complete, we
use the join() method.
t1.join()
t2.join()

As a result, the current program will first wait for the completion of t1 and then t2. Once, they
are finished, the remaining statements of the current program are executed.

Example:
Let us consider a simple example using a threading module.

# Python program to illustrate the concept


# of threading
# importing the threading module
import threading

def print_cube(num):
# function to print cube of given num
print("Cube: {}" .format(num * num * num))

def print_square(num):
# function to print square of given num
print("Square: {}" .format(num * num))

if __name__ =="__main__":
# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))

# starting thread 1
t1.start()
# starting thread 2
t2.start()

# wait until thread 1 is completely executed


t1.join()
# wait until thread 2 is completely executed
t2.join()

# both threads completely executed


print("Done!")

Output:
Square: 100
Cube: 1000
Done!

Synchronizing Threads in Python


The threading module provided with Python includes a simple-to-implement locking mechanism that allows
you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock.
The acquire(blocking) method of the new lock object is used to force threads to run synchronously. The
optional blocking parameter enables you to control whether the thread waits to acquire the lock.
If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with
a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released.
The release() method of the new lock object is used to release the lock when it is no longer required.

Example
#!/usr/bin/python
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"

When the above code is executed, it produces the following result −


Starting Thread-1
Starting Thread-2
Thread-1: Thu Mar 21 09:11:28 2013
Thread-1: Thu Mar 21 09:11:29 2013
Thread-1: Thu Mar 21 09:11:30 2013
Thread-2: Thu Mar 21 09:11:32 2013
Thread-2: Thu Mar 21 09:11:34 2013
Thread-2: Thu Mar 21 09:11:36 2013
Exiting Main Thread

Creating child process using fork() in Python


Our task is to create a child process and display process id of both parent and child process using fork()
function in Python.
When we use fork(), it creates a copy of itself, it is a very important aspect of LINUX, UNIX. fork() is mainly
applicable for multithreading environment that means the execution of the thread is duplicated created a
child thread from a parent thread. When there is an error, the method will return a negative value and for
the child process, it returns 0, Otherwise, it returns positive value that means we are in the parent process.
The fork() module can be used from the os module or from Pseudo terminal module called pty. So we should
import os or pty for it.
The fork() is used to create a process, it has no argument and its return the process ID. The main reason for
using fork() to create a new process which becomes the child process of the caller. When a new child process
is created, both processes will execute the next instruction.
The return value of fork() we can understand which process we are when return 0 that means we are in the
child process and if return positive value that means we are in the parent process and return negative value
means that some error occurred.

Example code
import os
def parentchild():
n = os.fork()
if n > 0:
print("Parent process : ", os.getpid())
else:
print("Child proces : ", os.getpid())
# Driver code
parentchild()
Output
Parent process : 8023
Child process : 8024
$
The Pseudo-terminal utility module pty is defined to handle pseudo-terminal concepts. Using this we can
start another process, and also can read or write from controlling terminal using programs.
This module is highly platform oriented. We should use UNIX systems to perform these operations.

Example code
import pty, os
def process_parent_child():
(process_id, fd) = pty.fork()
print("The Process ID for the Current process is: " + str(os.getpid()))
print("The Process ID for the Child process is: " + str(process_id))
process_parent_child()

Output
The Process ID for the Current process is: 12508
The Process ID for the Child process is: 12509

You might also like