Python Development Environment

Ratings:
(4)
Views: 761
Banner-Img
Share this blog:

 

Introduction

Python has been my go-to language through the years for everything from class projects in college to tiny scripts to help me automate recurring tasks. It's one of few languages out there that is both easy to get started with for beginners yet incredibly powerful when beginners graduate to working on real-world projects.

To edit Python programs, you have a number of options. Some people still prefer a basic text editor, like Emacs, Vim, or Gedit, all of which can be extended with features like syntax highlighting and autocomplete. But a lot of power users working on large projects with complex code bases prefer an integrated development environment (IDE) to the text editor plus terminal combination. The line between an advanced text editor and a slim IDE isn't always clear, and we'll leave it up to you to decide exactly which features you require for your development needs.

Python Development-specific IDEs

PyCharm is a Python-specific IDE built on JetBrains' platform. There are free editions for students and open-source projects.

Wing IDE is a paid development environment with integrated debugging and code completion.

PyDev is a Python IDE plugin for Eclipse.

Hosted development environment services

In the past couple of years, several cloud-based development environments have popped up. These can work great for when you're learning or stuck on a machine with only a browser but no way to install your own software. Most of these have free tiers for getting started and paid tiers as you scale up your application.

  • Nitrous.io
  • Cloud9
  • Terminal
  • Coding

Inclined to build a profession as Python Developer? Then here is the blog post on, explore Python Training

Development environment resources

  • If you're considering the cloud-based development environment route, check out this great article comparing Cloud9, Koding and Nitrous.io by Lauren Orsini. She also explains more about what a cloud IDE is and is not.
  • Real Python has an awesome, detailed post on setting up your Sublime Text 3 environment as a full-fledged IDE.
  • The Hitchhiker's Guide to Python has a page dedicated to development environments.
  • Choosing the best Python IDE is a review of six IDEs. PyCharm, Wing IDE and PyDev stand out above the other three in this review.
  • PyCharm: The Good Parts shows you how to be more efficient and productive with that IDE if it's your choice for writing Python code.
  • JetBrains' PyCharm Blog is required reading if you're using the IDE or considering trying it. One of the core developers also has an interview on the Talk Python to Me podcast that's worth listening to.
  • PyCharm vs Sublime Text has a comparison of several features between the two editors.

How to Connect to MySQL Using Python?

Python is easy to learn and use. The use of Python for web development is gradually but surely increasing as suggested by Google Trends. Python Web Development Trend

Python web development is a huge topic. There are a number of ways how we can proceed and it’s something that cannot be explained in a single article. Instead, we will learn how to connect a database (MySQL) in Python, a beginning step towards Python web development. There is a number of ways to connect MySQL using Python. Some of them are:

MySQLdb: a thread-compatible interface to MySQL

Mysql-connector-python: MySQL driver is written in Python

PyMySQL: a pure-Python MySQL driver

In this article, we will use PyMySQL to connect MySQL using Python. The benefits of using PyMySQL will be discussed later in the article once we learn how to use it.

Prerequisites

  • Python >= 2.6 or >= 3.3.
  • MySQL should be installed. Visit this page to Download MySQL and install it.
  • the pip package manager should be installed. If you have installed Python releases after 2.7.9 or 3.4, you already have pip.To update to the latest version, issue the following commands.

On Windows: python -m pip install -U pip setup tools

On Linux or macOS: pip install -U pip setup tools

Install pyMySQL

To install pyMySQL, simply issue the following command: pip install PyMySQL

Connect to MySQL Using Python

How to create a MySQL table in Python?

Create a database using MySQL Workbench, phpMyAdmin or any other tool you prefer. We will create python_tekslate database for our use.

Import pymysql and cursors using

  import pymysql.cursors
  import pymysql

Here, pymysql.cursor imports object to interact with the MySQL database.

To connect to our database,

connection = pymysql.connect( host = 'localhost', user = 'root', password = 'password', db = 'python_tekslate', charset = 'utf8', cursorclass = pymysql.cursors.DictCursor)

Note: You may need to modify the above code (user, password, db etc.) to work.

For now, we will simply create a user table with a column name.

  sql = "CREATE TABLE IF NOT EXISTS users (name VARCHAR(100) NOT NULL PRIMARY KEY)" 
  cursor = connection.cursor()
  execute(sql)

Here, we created a sql variable to put SQL query. Then, the query is executed.

Then the connection is committed to take effect.

commit()

Finally, close the cursor.

close()

Here is the complete code to create a new table in our database:

import pymysql.cursors
import pymysql
connection = pymysql.connect( host = 'localhost',
                           user = 'root',
                           password = 'admin',
                           db = 'test',
                           charset = 'utf8',
                           cursorclass = pymysql.cursors.DictCursor)
sql = "CREATE TABLE IF NOT EXISTS users (name VARCHAR(100) NOT NULL PRIMARY KEY)"
cursor = connection.cursor()
cursor.execute(sql)
connection.commit()
cursor.close()

Here are a few more examples:

Select Data from Table

import pymysql.cursors
import pymysql
connection = pymysql.connect( host = 'localhost',
                           user = 'root',
                           password = 'admin',
                           db = 'test',
                           charset = 'utf8',
                           cursorclass = pymysql.cursors.DictCursor)
try:
    with connection.cursor() as cursor:
        # Read all record from users table
        sql = "SELECT name FROM users"
        cursor.execute(sql)
        result = cursor.fetchall()
        print(result)
finally:
    connection.close()

Suppose, the user table has two rows of data Bill and Jack. Then, you will get the following output:

[{'name': Bill}, {'name': 'Jack'}]

Now, you can easily manipulate the result however you wish. If the table is empty, None object is returned. Here, we have used Python try…finally statement for safety. If there is a problem with executing our code, the connection is closed. Also, the cursor (created by the connection.cursor()) is closed when there is a problem with the cursor. We have used with statement to accomplish this task.

Insert Data Into Table

import pymysql.cursors
import pymysql
connection = pymysql.connect( host = 'localhost',
                           user = 'root',
                           password = 'admin',
                           db = 'test',
                           charset = 'utf8',
                           cursorclass = pymysql.cursors.DictCursor)
try:
    with connection.cursor() as cursor:
        # New record is created in users table
        sql = "INSERT INTO users (`name`) VALUES (%s);"
        cursor.execute(sql, 'Bill')
        connection.commit()
finally:
    connection.close()

Here, Bill is inserted to the name column of users table.

Note: You need to commit the connection manually while inserting data.

Creating the Database

Not only pyMySQL allows you to connect to the database, it can be used to create the database as well.

import pymysql.cursors
import pymysql
connection = pymysql.connect( host = 'localhost',
                           user = 'root',
                           password = 'admin',
                           charset = 'utf8',
                           cursorclass = pymysql.cursors.DictCursor)
cursor = connection.cursor()
# database name
database = 'node'
cursor.execute("CREATE DATABASE IF NOT EXISTS " + database)
connection.commit()
cursor.close()

We created a new database node in the above code. If the database already exists, it will remain unchanged.

Advantages of Using pyMySQL

  • pyMySQL is a pure-Python MySQL client library and hence there are no external dependencies.
  • The installation process is easy and consistent overall operating systems.
  • It is fully open-source and released under MIT license. So you can redistribute it without any issues.
  • It is fully compatible with both Python 2 and Python 3.
  • It is actively maintained and supported.

Also, I would suggest you learn Python’s SQLAlchemy. It’s an open-source toolkit and ORM (Open-Relational-Mapper) for Python programming. You can avoid writing error-prone raw SQL statements that are hard to maintain.  

For an In-depth knowledge on Python, click on below

You liked the article?

Like: 0

Vote for difficulty

Current difficulty (Avg): Medium

EasyMediumHardDifficultExpert
IMPROVE ARTICLEReport Issue

About Author

Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated
Get stories of change makers and innovators from the startup ecosystem in your inbox