Found 10784 Articles for Python

Starting a New Thread in Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:08:18

485 Views

To spawn another thread, you need to call following method available in thread module −thread.start_new_thread ( function, args[, kwargs] )This method call enables a fast and efficient way to create new threads in both Linux and Windows.The method call returns immediately and the child thread starts and calls function with the passed list of args. When function returns, the thread terminates.Here,  args is a tuple of arguments; use an empty tuple to call function without passing any arguments. kwargs is an optional dictionary of keyword arguments.Example#!/usr/bin/python import thread import time # Define a function for the thread def print_time( threadName, delay):    count = 0   ... Read More

Sending Attachments as an E-mail using Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:09:56

585 Views

To send an e-mail with mixed content requires to set Content-type header to multipart/mixed. Then, text and attachment sections can be specified within boundaries.A boundary is started with two hyphens followed by a unique number, which cannot appear in the message part of the e-mail. A final boundary denoting the e-mail's final section must also end with two hyphens.Attached files should be encoded with the pack("m") function to have base64 encoding before transmission.ExampleFollowing is the example, which sends a file /tmp/test.txt as an attachment. Try it once −#!/usr/bin/python import smtplib import base64 filename = "/tmp/test.txt" # Read a file and ... Read More

Sending an HTML e-mail using Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:05:04

629 Views

When you send a text message using Python, then all the content are treated as simple text. Even if you include HTML tags in a text message, it is displayed as simple text and HTML tags will not be formatted according to HTML syntax. But Python provides option to send an HTML message as actual HTML message.While sending an e-mail message, you can specify a Mime version, content type and character set to send an HTML e-mail.ExampleFollowing is the example to send HTML content as an e-mail. Try it once −#!/usr/bin/python import smtplib message = """From: From Person To: ... Read More

Database Handling Errors in Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:03:40

3K+ Views

There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle.The DB API defines a number of errors that must exist in each database module. The following table lists these exceptions.Sr.No.Exception & Description1WarningUsed for non-fatal issues. Must subclass StandardError.2ErrorBase class for errors. Must subclass StandardError.3InterfaceErrorUsed for errors in the database module, not the database itself. Must subclass Error.4DatabaseErrorUsed for errors in the database. Must subclass Error.5DataErrorSubclass of DatabaseError that refers to errors in the data.6OperationalErrorSubclass of DatabaseError ... Read More

Disconnecting Database in Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:02:53

5K+ Views

To disconnect Database connection, use close() method.db.close()If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly.

Commit & RollBack Operation in Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:02:15

518 Views

COMMITCommit is the operation, which gives a green signal to database to finalize the changes, and after this operation, no change can be reverted back.Here is a simple example to call commit method.db.commit()ROLLBACKIf you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use rollback() method.Here is a simple example to call rollback() method.db.rollback()

Performing Database Transactions using Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:01:40

992 Views

Transactions are a mechanism that ensures data consistency. Transactions have the following four properties −Atomicity − Either a transaction completes or nothing happens at all.Consistency − A transaction must start in a consistent state and leave the system in a consistent state.Isolation − Intermediate results of a transaction are not visible outside the current transaction.Durability − Once a transaction was committed, the effects are persistent, even after a system failure.The Python DB API 2.0 provides two methods to either commit or rollback a transaction.ExampleYou already know how to implement transactions. Here is again similar example −# Prepare SQL query to DELETE required records sql ... Read More

Database DELETE Operation in Python

Mohd Mohtashim
Updated on 31-Jan-2020 10:00:42

206 Views

DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20 −Example#!/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() # Prepare SQL query to DELETE required records sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20) try:    # Execute the SQL command    cursor.execute(sql)    # Commit your changes in the database    db.commit() except:    # Rollback in case ... Read More

Database Update Operation in Python

Mohd Mohtashim
Updated on 31-Jan-2020 09:59:37

378 Views

UPDATE Operation on any database means to update one or more records, which are already available in the database.The following procedure updates all the records having SEX as 'M'. Here, we increase AGE of all the males by one year.Example#!/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() # Prepare SQL query to UPDATE required records sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M') try:    # Execute the SQL command    cursor.execute(sql)    # Commit your ... Read More

Database READ Operation in Python

Mohd Mohtashim
Updated on 31-Jan-2020 09:58:22

588 Views

READ Operation on any database means to fetch some useful information from the database.Once our database connection is established, you are ready to make a query into this database. You can use either fetchone() method to fetch single record or fetchall() method to fetech multiple values from a database table.fetchone() − It fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table.fetchall() − It fetches all the rows in a result set. If some rows have already been extracted from the result ... Read More

Advertisements