Daisy Rees

Daisy Rees

1564847334

Getting Started with MySQL in Python

MySQL Python: About MySQL

  • MySQL is a fast, easy-to-use relational database. It is currently the most popular open-source database
  • MySQL is used for many small and big businesses. It is developed, marketed, and supported by MySQL AB, a Swedish company. It is written in C and C++.
  • MySQL is an open-source database, so you don’t have to pay a single penny to use it.

Download MySQL

Follow these steps:

  1. Go to the official MySQL website
  2. Choose the version number for the MySQL community server that you want.

MySQL Python Connector

MySQL Python Connector is used to access the MySQL database from Python. You need a database driver.

MySQL Connector/Python is a standardized database driver provided by MySQL.

To check whether the mysql.connector is available or not, we type the following command:

>>> import mysql.connector

After typing this, we clearly say that No Module Named MySQL is present.

Then, we have to install MySQL. Python needs a MySQL driver to access the MySQL database.

So, next, we download the mysql-connector with the use of pip.

C:\Users\Nitin Arvind Shelke>pip install mysql-connector

After installation, we test whether it works or not. Lets check with the following command:

>>> import mysql.connector

The above line imports the MySQL Connector Python module in your program, so you can use this module’s API to connect MySQL.

If the above code was executed with no errors, we can say that “MySQL Connector” is installed properly and get ready to use it.

>>>from mysql.connector import Error

The MySQL connector error object is used to show us an error when we failed to connect databases or if any other database error occurred while working with the database.

Creating a Connection to the Database

After installing the MySQL Python connector, we need to test it to make sure that it is working correctly, and you can connect to the MySQL database server without any problems. To verify the installation, use the following steps:

Type the following line of code:

>>> import mysql.connector
To establish a connection to the database we should know the following parameters,
Host= localhost (In general it is same for all)
Database=mysql (You can set as per your wish)
User=root (It is a username)
Password= root@123 (password set by me while installation of MyQL)
>>> mysql.connector.connect( host = 'localhost', database = 'mysql', user = 'root', password = 'root@123')

Show the Available Database

You can check if a database exists on your system by listing all the databases in your system by using the “SHOW DATABASES” statement:

>>> my_database = mysql.connector.connect( host = 'localhost', database = 'mysql', user = 'root', password = 'root@123')
>>> cursor = my_database.cursor()
>>> cursor.execute( " show databases " )
>>> for db in cursor:
...  print(db)
...

Output

('bank',)
('information_schema',)
('mysql',)
('performance_schema',)
('sakila',)
('sys',)
('world',)
>>>

Creating a Database

To create a database in MySQL, we use the “CREATE DATABASE” statement to create the database named “college”:

>>> my_database = mysql.connector.connect( host = 'localhost', user = 'root', password = 'root@123' )
>>> cursor = my_database.cursor()
>>> cursor.execute( " CREATE DATABASE college "  )
>>> for db in cursor:
...  print(db)
...
>>> cursor.execute( " show databases " )
>>> for db in cursor:
...  print(db)
...

Creating the Tables

Next, we create the tables for the ‘college’ database.

It is compulsory to define the name of the database while creating the tables for it.

Syntax to create the table is

create table_name(
column 1 datatype,
column 2 datatype,
column 3 datatype,
…………………………………………,
column n datatype
)

Let’s create the table students, department, and faculty for the database college.

>>> my_database = mysql.connector.connect ( host = 'localhost', database = 'college', user = 'root', password = 'root@123' )
>>> cursor = my_database.cursor()
>>>cursor. execute( " CREATE TABLE students ( stud_id varchar(200), stud_name VARCHAR(215), address VARCHAR(215), city char(100)) " )
>>> cursor. execute( " CREATE TABLE department ( dept_id varchar(200), dept_name VARCHAR(215)) " )
>>> cursor.execute( "CREATE TABLE faculty (  faculty_id varchar(200),faculty_name VARCHAR(215) )"  )

Show the Tables

To display the tables, we will have to use the “SHOW TABLES”

The following code displays all the tables present in the database “college”

>>> cursor. execute ( " SHOW TABLES " )
>>> for x in cursor:
...      print(x)
...
('department',)
('faculty',)
('students',)

Assign Primary Key in Table

Primary key: It is a minimal set of attributes (columns) in a table or relation that can uniquely identify tuples (rows) in that table.

For example, Student (Stud_Roll_No, Stud_Name, Addr)

In the student relation, attribute StudRollNo alone is a primary key, as each student has a unique id that can identify the student record in the table.

>>> my_database = mysql.connector.connect ( host = 'localhost', database = 'college', user = 'root', password = 'root@123' )
>>> cursor = my_database.cursor()
>>>cursor. execute( " CREATE TABLE students2 ( stud_id varchar(200) PRIMARY KEY, stud_name VARCHAR(215), address VARCHAR(215), city char(100)) " )

If the table already exists, use the ALTER TABLE keyword:

>>> my_database = mysql.connector.connect ( host = 'localhost', database = 'college', user = 'root', password = 'root@123' )
>>> cursor = my_database.cursor()
>>>cursor.execute( " ALTER TABLE student ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY " )

Describe the Created Tables

Desc keyword is used to describe the table in MySQL.

The following code describes the students table from the college database:

>>> cursor.execute("desc students")
>>> for x in cursor:
...     print(x)
...
('stud_id', 'varchar(200)', 'YES', '', None, '')
('stud_name', 'varchar(215)', 'YES', '', None, '')
('address', 'varchar(215)', 'YES', '', None, '')
('city', 'char(100)', 'YES', '', None, '')
>>>

Example 2

The following code describes the students2 (where stud_id is mentioned as primary key) table from the college database:

>>> cursor.execute("desc students2")
>>> for x in cursor:
...     print(x)
...
('stud_id', 'varchar(200)', 'NO', 'PRI', None, '')
('stud_name', 'varchar(215)', 'YES', '', None, '')
('address', 'varchar(215)', 'YES', '', None, '')
('city', 'char(100)', 'YES', '', None, '')
>>>

Insert Data Into the Table

To insert the data into the table, the “insert into” statement is used.

Let’s insert the data into the students table of the college database,

>>> my_database = mysql.connector.connect ( host = 'localhost', database = 'college', user = 'root', password = 'root@123' )
>>> stm = " INSERT INTO students ( stud_id, stud_name, address, city ) VALUES ('101','Nitin Shelke', 'Congress Nagar', 'Amravati' ) "
>>> cursor = my_database.cursor()
>>> cursor.execute(stm)

Display or Select the Inserted Data From the Table

>>> cursor.execute(" select * from students")
>>> for x in cursor:
...     print(x)
...
('101', 'Nitin Shelke', 'Congress Nagar', 'Amravati')

An alternate way is to use the fetchall() method.

>>> cursor.fetchall()
[(‘101’, ‘Nitin Shelke’, ‘Congress Nagar’, ‘Amravati’)]

Thanks for reading! Let me know your thoughts in the comments.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Python

Complete Python Bootcamp: Go from zero to hero in Python 3

Machine Learning A-Z™: Hands-On Python & R In Data Science

Python and Django Full Stack Web Developer Bootcamp

Complete Python Masterclass

Python Tutorial - Python GUI Programming - Python GUI Examples (Tkinter Tutorial)

Computer Vision Using OpenCV

OpenCV Python Tutorial - Computer Vision With OpenCV In Python

Python Tutorial: Image processing with Python (Using OpenCV)

A guide to Face Detection in Python

Machine Learning Tutorial - Image Processing using Python, OpenCV, Keras and TensorFlow

PyTorch Tutorial for Beginners

#mysql #python #database

What is GEEK

Buddha Community

Getting Started with MySQL in Python
Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Joe  Hoppe

Joe Hoppe

1595905879

Best MySQL DigitalOcean Performance – ScaleGrid vs. DigitalOcean Managed Databases

HTML to Markdown

MySQL is the all-time number one open source database in the world, and a staple in RDBMS space. DigitalOcean is quickly building its reputation as the developers cloud by providing an affordable, flexible and easy to use cloud platform for developers to work with. MySQL on DigitalOcean is a natural fit, but what’s the best way to deploy your cloud database? In this post, we are going to compare the top two providers, DigitalOcean Managed Databases for MySQL vs. ScaleGrid MySQL hosting on DigitalOcean.

At a glance – TLDR
ScaleGrid Blog - At a glance overview - 1st pointCompare Throughput
ScaleGrid averages almost 40% higher throughput over DigitalOcean for MySQL, with up to 46% higher throughput in write-intensive workloads. Read now

ScaleGrid Blog - At a glance overview - 2nd pointCompare Latency
On average, ScaleGrid achieves almost 30% lower latency over DigitalOcean for the same deployment configurations. Read now

ScaleGrid Blog - At a glance overview - 3rd pointCompare Pricing
ScaleGrid provides 30% more storage on average vs. DigitalOcean for MySQL at the same affordable price. Read now

MySQL DigitalOcean Performance Benchmark
In this benchmark, we compare equivalent plan sizes between ScaleGrid MySQL on DigitalOcean and DigitalOcean Managed Databases for MySQL. We are going to use a common, popular plan size using the below configurations for this performance benchmark:

Comparison Overview
ScaleGridDigitalOceanInstance TypeMedium: 4 vCPUsMedium: 4 vCPUsMySQL Version8.0.208.0.20RAM8GB8GBSSD140GB115GBDeployment TypeStandaloneStandaloneRegionSF03SF03SupportIncludedBusiness-level support included with account sizes over $500/monthMonthly Price$120$120

As you can see above, ScaleGrid and DigitalOcean offer the same plan configurations across this plan size, apart from SSD where ScaleGrid provides over 20% more storage for the same price.

To ensure the most accurate results in our performance tests, we run the benchmark four times for each comparison to find the average performance across throughput and latency over read-intensive workloads, balanced workloads, and write-intensive workloads.

Throughput
In this benchmark, we measure MySQL throughput in terms of queries per second (QPS) to measure our query efficiency. To quickly summarize the results, we display read-intensive, write-intensive and balanced workload averages below for 150 threads for ScaleGrid vs. DigitalOcean MySQL:

ScaleGrid MySQL vs DigitalOcean Managed Databases - Throughput Performance Graph

For the common 150 thread comparison, ScaleGrid averages almost 40% higher throughput over DigitalOcean for MySQL, with up to 46% higher throughput in write-intensive workloads.

#cloud #database #developer #digital ocean #mysql #performance #scalegrid #95th percentile latency #balanced workloads #developers cloud #digitalocean droplet #digitalocean managed databases #digitalocean performance #digitalocean pricing #higher throughput #latency benchmark #lower latency #mysql benchmark setup #mysql client threads #mysql configuration #mysql digitalocean #mysql latency #mysql on digitalocean #mysql throughput #performance benchmark #queries per second #read-intensive #scalegrid mysql #scalegrid vs. digitalocean #throughput benchmark #write-intensive

Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

Art  Lind

Art Lind

1602968400

Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development