Issuing update query in Python script

Lesson Details:
June 29, 2020


I: Introduction

Python is an open source programming language. It is widely used for general purpose, scientific, mathematical and web development. It is easy to learn and versatile. You can start learning python by reading our tutorials or follow our online course on python programming.

II: Body

I will be telling you about Issuing update query in python. Let us try to understand it with the help of example.

Suppose you are working as a database administrator of company ABC. One day your boss gave you a task of issuing an update query on the database of company XYZ. For this, he sent you the file which contains the query statement. You need to write a python script to execute that query statement.

You first need to import the modules required for executing that query statement. You do it by using below commands.

import csv, os, shutil, sys, glob, re

Then you need to open the file containing the query statement using below command.

file = open(“/home/abc/xyz_update_query.csv”)

After opening the file, you can read the contents of the file using next lines of code.

with open(file, “r”) as f: content = csv.reader(f)

Now you can read each row of that file by iterating over the content variable.

for row in content: print row

After reading each row of that file, you can check whether you have executed the query successfully by comparing the output with expected output which was given by your boss. If it matches, then you can write ‘success’ in the text file. Otherwise, you can write ‘failure’ in the text file. This will be done using below commands.

out = open(“/home/abc/xyz_result_test”, “w”) if row == “success”: out.write(row) else: out.write(“failure”) out.close()

loader
Course content