Data Base Programming

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Data base programming

Python being a high-level language provides support for various databases.

We can connect and run queries for a particular database using Python and without writing raw queries in the
terminal or shell of that particular database, we just need to have that database installed in our system.

MySQL-Connector-Python module in Python

MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language
(SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating
and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create
signify the same command.

For any application, it is very important to store the database on a server for easy data access.

What is MYSQL Connector/Python?

MySQL Connector/Python enables Python programs to access MySQL databases, using an API that is
compliant with the Python Database API Specification v2.0 (PEP 249). It is written in pure Python and does not
have any dependencies except for the Python Standard Library.

There are various versions of MySQL Connector/Python available:

Installing module

This module does not come built-in with Python. To install it type the below command in the terminal.

pip install mysql-connector-python

If any issue is there while installing, one can explicitly specify the module version as follows:

pip install mysql-connector-python==8.0.17


Verifying MySQL Connector/Python installation

After installing the MySQL Python connector, we need to test it to make sure that it is working correctly and we
are able to connect to the MySQL database server without any issues.

To verify the installation, we can use the following steps:

Open Python command line

Type the following code

Installation procedure in youtube channel https://www.youtube.com/watch?v=MhaH7o3lf4E&t=184s

Interacting with a database is an important feature in many programming languages including


python.

In comparision to storing data in flatfiles, its much easier to store, retrive and modify data in a database. We are
going to learn the

following concepts and programming skills.

Creating a Database connection

Creating a Database

Create a Table

Inserting into the table

Retrieving data from Table

Updating Records in a table

Deleting Data in a table

Before you can start working with MySQL database, you need to start the database server. I am using WAMP
server for this tutorial. You also need to install the latest mysql-connetor for this purpose. use pip install mysql-
connector in the command window to download and install it.

In [4]: import mysql.connector

mysql.connector.connect(host='localhost',
user='root',
password="123456")

Out[4]: <mysql.connector.connection_cext.CMySQLConnection at 0x1bb35940640>


If you see the following output, it means that you have been successfully installing the MySQL
Connector/Python on your system.

Connect MySQL database using MySQL-Connector


Python

While working with Python we need to work with databases, they may be of different types like MySQL,
SQLite, NoSQL, etc.

MySQL Connector module of Python is used to connect MySQL databases with the Python programs, it
does that using the Python Database API Specification v2.0 (PEP 249). It uses the Python standard
library and has no dependencies.

Connecting to the Database


In the following example we will be connecting to MySQL

database using connect()

In [1]: # Python program to connect to mysql database


import mysql.connector
conn=mysql.connector.connect(host='localhost',
user='root',
password="123456")
print(conn)
# Disconnecting from the server
conn.close()

<mysql.connector.connection_cext.CMySQLConnection object at 0x00000229437EE55


0>
Python MySQL – Create Database

Python Database API ( Application Program Interface ) is the Database interface for the standard Python. There
are various Database servers supported by Python Database such as MySQL

GadFly

mSQL

PostgreSQL

Microsoft,

SQL Server 2000

Informix,

Interbase

Oracle,

Sybase etc.

To connect with MySQL database server from Python, we need to import the mysql.connector interface.

Syntax:

CREATE DATABASE DATABASE_NAME

The above program illustrates the creation of MySQL database geeks4geeks in which host-name is
localhost, the username is user and password is gfg.

Let’s suppose we want to create a table in the database, then we need to connect to a database. Below is a
program to create a table in the geeks4geeks database which was created in the above program.
Python: MySQL Create Table
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL)
is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting
the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same
command.

Installation

Follow the below-mentioned process for installing the dependencies for python MySQL

Navigate to the python script directory using the command prompt. Execute the command

pip install mysql-connector

Python Mysql Connector Module Methods

1. connect(): This function is used for establishing a connection with the MySQL server. The following are the
arguments that are used to initiate a connection:

(a) user: User name associated with the MySQL server used
to authenticate the connection

(b) password: Password associated with the user name for


authentication

(c) database: Data base in the MySQL for creating the Table

1. cursor(): Cursor is the workspace created in the system memory when the SQL command is executed. This
memory is temporary and the cursor connection is bounded for the entire session/lifetime and the
commands are executed

1. execute(): The execute function takes a SQL query as an argument and executes. A query is an SQL
command which is used to create, insert, retrieve, update, delete etc.

cursor () is used to create a cursor instance/ object


After establishing the connection between Python and MySQL database. The database cursor is a control
structure, which enables us to make traversal over the records / rows in a database. A cursor can be treated a
pointer to the first row / tuple of the set of the records stored in the database. Like a file pointer which is pointing
to current record / object of the file, moves automatically to next record and finally reaches the end of the file, the
cursor points to the first row, then automatically travels to other rows of the database and finally reaches end of
the table. Thus, the cursor facilitates retrieve, addition, updating and deletion of database records. Once we have
created a cursor instance /object, we can execute various types of SQL queries using the method execute() to
manipulate the records of the database linked with the Python.
Data Base

The database is an organization of information structured into multiple tables. Databases are organized in such a
way so that manipulating the data is easy i.e Creating, inserting, updating, and deleting etc.

SQL command for Creating Database :

CREATE DATABASE ;

Example: Consider the below example for creating a database in MySQL(Ex: college)

In [3]: import mysql.connector# step 1


#Create the connection object
con = mysql.connector.connect(host = "localhost",
user ="root",
password ="123456") # step 2
#creating the cursor object
mycursor = con.cursor() # step 3
#executing the query
print("List of databases: ")
#Retrieving the list of databases
dbs = mycursor.execute("SHOW databases"); # step 4
#display the result
for x in mycursor:
print(x)
#close the connection
con.close()# step 5

List of databases:
('college',)
('information_schema',)
('mysql',)
('performance_schema',)
('student',)
('students',)
('sys',)
In [4]: import mysql.connector

# Open database connection


con = mysql.connector.connect(host = "localhost",
user ="root",
password ="123456")

# prepare a cursor object using cursor() method


mycursor = con.cursor()

# execute SQL query using execute() method.


mycursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.


data = mycursor.fetchone()
print("Database version : %s " % data)

# disconnect from server


con.close()

Database version : 8.0.31

If a connection is established with the datasource, then a Connection Object is returned and saved into
db for further use, otherwise db is set to None. Next, db object is used to create a cursor object, which in
turn is used to execute SQL queries. Finally, before coming out, it ensures that database connection is
closed and resources are released.

Creating Database Table


Once a database connection is established, we are ready to create tables or records into the database tables
using execute method of the created cursor.

Example

Let us create Database table EMPLOYEE −

Creating a Database

After establishing connection with MySQL, to manipulate data in it you need to connect to a database.
You can connect to an existing database or, create your own.

You would need special privileges to create or to delete a MySQL database. So if you have access to the root
user, you can create any database.
In [5]: import mysql.connector
con = mysql.connector.connect(host = "localhost",
user ="root",
password ="123456")
mycursor = con.cursor()
mycursor.execute("Drop DataBASE IF EXISTS student")
mycursor.execute("CREATE DATABASE student")
mycursor.execute("USE student")

Creating the Table


Once a database connection is established, we are ready to create tables or records into the database tables
using execute method of the created cursor.

The CREATE TABLE statement is used to create tables in MYSQL database. Here, you need to specify the
name of the table and, definition (name and datatype) of each column.

Syntax:

Following is the syntax to create a table in MySQL:

CREATE TABLE table_name(column1 datatype,

column2 datatype,

column3 datatype, .....

columnN datatype,

);

The DESC statement gives you the description of the specified table.

Using this you can verify if the table has been created or not as shown below:

mysql> Desc Employee;


Creating a table in MySQL using python
The method named execute() (invoked on the cursor object) accepts two variables:

1. A String value representing the query to be executed.


2. An optional args parameter which can be a tuple or, list or, dictionary, representing the parameters of the
query (values of the place holders).

It returns an integer value representing the number of rows effected by the query. Once a database connection is
established, you can create tables by passing the CREATE TABLE query to the execute() method.

In short, to create a table using python:

1.Import mysql.connector package.

2.Create a connection object using the mysql.connector.connect() method, by passing the user name, password,
host (optional default: localhost) and, database (optional) as parameters to it.

3.Create a cursor object by invoking the cursor() method on the connection object created above.

4.Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method.

In [6]: import mysql.connector


#establishing the connection
con = mysql.connector.connect(host = "localhost",
user ="root",
password ="123456",database="student")
#Creating a cursor object using the cursor() method
mycursor = con.cursor()

#Droping database MYDATABASE if already exists.


mycursor.execute("DROP TABLE IF EXISTS studentinfo")
#Creating the Table
mycursor.execute("CREATE TABLE studentinfo (name VARCHAR(30), age INT(3), gend
er CHAR(1))")
Inserting data into the table
Can add new rows to an existing table of MySQL using the INSERT INTO statement.

In this, need to specify the name of the table, column names, and values (in the same order as column names).

Syntax:

Following is the syntax of the INSERT INTO statement of MySQL. INSERT INTO TABLE_NAME (column1,
column2, column3,...columnN) VALUES (value1, value2, value3,...valueN);

Example:

Following query inserts a record into the table named studentinfo .

INSERT INTO studentinfo(name, age, gender) VALUES ('Mech','20', F);

You can verify the records of the table after insert operation using the SELECT statement as:

mysql> select * from studentinfo;

It is not mandatory to specify the names of the columns always, if you pass values of a record in the same order
of the columns of the table you can execute the SELECT statement without the column names as follows:

INSERT INTO EMPLOYEE VALUES ('Mac', 'Mohan', 20, 'M', 2000);

In [6]: import mysql.connector


con = mysql.connector.connect(host = "localhost",
user ="root",
password ="123456")
mycursor = con.cursor()
mycursor.execute("DROP DATABASE IF EXISTS student")
mycursor.execute("CREATE DATABASE student")
mycursor.execute("USE student")
mycursor.execute("DROP TABLE IF EXISTS studentinfo")
mycursor.execute("CREATE TABLE studentinfo (name VARCHAR(30), age INT(3), gend
er CHAR(1))")
##Inserting data into the table
#Preparing query to create a database
sql = """INSERT INTO studentinfo(name, age, gender)
VALUES('Ashok',17,'M')"""
mycursor.execute(sql)
con.commit()

Inserting multiple rows simultaniously


Here we are going to use the executemany() function that accept two parameters as shown below.
In [7]: import mysql.connector
con = mysql.connector.connect(host = "localhost",
user ="root",
password ="123456")
mycursor = con.cursor()
mycursor.execute("DROP DATABASE IF EXISTS student")
mycursor.execute("CREATE DATABASE student")
mycursor.execute("USE student")
mycursor.execute("DROP TABLE IF EXISTS studentinfo")
mycursor.execute("CREATE TABLE studentinfo (name VARCHAR(30), age INT(3), gend
er CHAR(1))")
#Inserting multiple rows simultaniously
sql = """INSERT INTO studentinfo(name, age, gender)
VALUES(%s, %s, %s)"""
rows = [('Amit', 21,'M'),('Sudha', 17, 'F')]
mycursor.executemany(sql, rows)
con.commit()
con.close()

Reading from 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 set,
then it retrieves the remaining rows from the result set.

In [8]: import mysql.connector


con = mysql.connector.connect(host = "localhost",
user ="root",
password ="123456",database="student")
mycursor = con.cursor()
sql = "SELECT * FROM studentinfo"
mycursor.execute(sql)
result = mycursor.fetchall()
for row in result:
name = row[0]
age = row[1]
gender = row[2]
print("Name=%s, Age=%d, Gender=%c" % (name,age,gender))
con.close()

Name=Amit, Age=21, Gender=M


Name=Sudha, Age=17, Gender=F

Updating records in a Table


In [11]: import mysql.connector
con = mysql.connector.connect(host = "localhost",
user ="root",
password ="123456",database="student")
mycursor = con.cursor()
sql = "UPDATE studentinfo SET age=age-3 WHERE age='%d'" % (17)
mycursor.execute(sql)
sql = "SELECT * FROM studentinfo"
mycursor.execute(sql)
result = mycursor.fetchall()
for row in result:
name = row[0]
age = row[1]
gender = row[2]
print("Name=%s, Age=%d, Gender=%c" % (name,age,gender))
con.close()

Name=Amit, Age=21, Gender=M


Name=Sudha, Age=14, Gender=F

In [ ]:

Deleting Records from a Table


In [12]: import mysql.connector
con = mysql.connector.connect(host = "localhost",
user ="root",
password ="123456",database="student")
mycursor = con.cursor()
sql = "DELETE FROM studentinfo WHERE name='%s'" % ('Amit')
mycursor.execute(sql)
sql = "SELECT * FROM studentinfo"
mycursor.execute(sql)
result = mycursor.fetchall()
for row in result:
name = row[0]
age = row[1]
gender = row[2]
print("Name=%s, Age=%d, Gender=%c" % (name,age,gender))
con.close()

Name=Sudha, Age=17, Gender=F

In [ ]: https://www.youtube.com/watch?v=MhaH7o3lf4E

You might also like