MySQL connector for Python

In this we can see the pure python way to access MySQL. In this session we learn
Creating Database, Creating Tables, Insert data into tables and Retreive data

This is to explain the basic workings of the connector (for a comprehensive way to implement mysql connector please see the docs at https://dev.mysql.com/doc/connector-python/en/index.html

Download and install the MySQL connector for python from
https://dev.mysql.com/downloads/connector/python/
 
Example: dbtest.py file
________________________________________________________________________________
import mysql.connector

def application(environ, start_response):
    write=start_response('200 OK', [('Content-Type', 'text/plain')])

    cnx = mysql.connector.connect(user='root', password='MyPassword',host='127.0.0.1')
    cursor = cnx.cursor()
  
    # Creating a Database
    cursor.execute("create database awesome")
  
    # selecting the database
    cnx.database="awesome"
  
    # Creating tables into database
    cursor.execute("CREATE TABLE `employees` ("
    "  `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
    "  `birth_date` date NOT NULL,"
    "  `first_name` varchar(14) NOT NULL,"
    "  `last_name` varchar(16) NOT NULL,"
    "  `gender` enum('M','F') NOT NULL,"
    "  `hire_date` date NOT NULL,"
    "  PRIMARY KEY (`emp_no`)"
    ") ENGINE=InnoDB")
  
    # Insert Data into tables
    cursor.execute("INSERT INTO employees "
               "(emp_no, birth_date, first_name, last_name, gender,hire_date) "
               "VALUES ('1001','26031980','PersonFirst','PersonLast','M','26031980')")
    cnx.commit()
    cursor.close()
    cnx.close()
  
    # Query the data and print into a table in html page

    query = "select * from employees"
    cursor.execute(query)

    yield """
    <html>
    <head>
     <link href='http://twitter.github.com/bootstrap/assets/css/bootstrap.css' rel='stylesheet'>    </head>
    <title>
    My WSGI with bootstrap
    </title>
    <body>
    <table class="table table-striped">
    <th> ID </th>
    <th> SIP </th>
    <th> Firstname </th>
    <th> Lastname </th>
    <th> MID </th>
    <th> POOL </th>
    <tr>
    """
    for val in cursor:
        for each in val:
            write('<td>'+str(each)+'</td>')
    yield "</tr>"

________________________________________________________________________________

2 comments:

  1. the blog is aboutAutomated data lineage documentation using #Python it is useful for students and Python Developers for more updates on python follow the link

    Python Online course

    For more info on other technologies go with below links

    tableau online training hyderabad

    ServiceNow Online Training

    mulesoft Online Training

    ReplyDelete