Chapter 5-1
Chapter 5-1
Negative Indexing
The tuple element can also access by using negative indexing. The index of -1 denotes the
rightmost element and -2 to the second last item and so on.
The elements from left to right are traversed using the negative indexing. Consider the following
example:
1. tuple1 = (1, 2, 3, 4, 5)
2. print(tuple1[-1])
3. print(tuple1[-4])
4. print(tuple1[-3:-1])
5. print(tuple1[:-1])
6. print(tuple1[-2:])
Output:
5
2
(3, 4)
(1, 2, 3, 4)
(4, 5)
Deleting Tuple
Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples are immutable.
To delete an entire tuple, we can use the del keyword with the tuple name.
Consider the following example.
1. tuple1 = (1, 2, 3, 4, 5, 6)
2. print(tuple1)
3. del tuple1[0]
4. print(tuple1)
5. del tuple1
6. print(tuple1)
Output:
In this section of the tutorial, we will discuss Python - MySQL connectivity, and we will perform the
database operations in python. We will also cover the Python connectivity with the databases like
MongoDB and SQLite later in this tutorial.
Install mysql.connector
To connect the python application with the MySQL database, we must import the mysql.connector
module in the program.
The mysql.connector is not a built-in module that comes with the python installation. We need to
install it to get it working.
3. Open the terminal (CMD for windows) and change the present working directory to the source code
directory.
1. $ cd mysql-connector-python-8.0.13/
4. Run the file named setup.py with python (python3 in case you have also installed python 2) with
the parameter build.
Database Connection
In this section of the tutorial, we will discuss the steps to connect the python application to the
database.
There are the following steps to connect a python application to our database.
To create a connection between the MySQL database and the python application, the connect()
method of mysql.connector module is used.
Pass the database details like HostName, username, and the database password in the method call.
The method returns the connection object.
Example
1. import mysql.connector
2. #Create the connection object
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", dat
abase = "mydb")
4. #printing the connection object
5. print(myconn)
Output:
The cursor object can be defined as an abstraction specified in the Python DB-API 2.0. It facilitates
us to have multiple separate working environments through the same connection to the database. We
can create the cursor object by calling the 'cursor' function of the connection object. The cursor object
is an important aspect of executing queries to the databases.
1. <my_cur> = conn.cursor()
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", dat
abase = "mydb")
4.
5. #printing the connection object
6. print(myconn)
7.
8. #creating the cursor object
9. cur = myconn.cursor()
The new database can be created by using the following SQL query.
('EmployeeDB',)
('PythonDB',)
('Test',)
('TestDB',)
('anshika',)
We can create the new table by using the CREATE TABLE statement of SQL. In our database
PythonDB, the table Employee will have the four columns, i.e., name, id, salary, and department_id
initially.
1. > create table Employee (name varchar(20) not null, id int primary key, salary float not null
, Dept_Id int not null)
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Creating a table with name Employee having four columns i.e., name, id, salary, and dep
artment id
11. dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20) not null pr
imary key, salary float not null, Dept_id int not null)")
12. except:
13. myconn.rollback()
14.
15. myconn.close()
Alter Table
Sometimes, we may forget to create some columns, or we may need to update the table schema. The
alter statement used to alter the table schema if required. Here, we will add the column branch_name
to the table Employee. The following SQL query is used for this purpose.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #adding a column branch name to the table Employee
11. cur.execute("alter table Employee add branch_name varchar(20) not null")
12. except:
13. myconn.rollback()
14.
15. myconn.close()
Insert Operation
Adding a record to the table
The INSERT INTO statement is used to add a record to the table. In python, we can mention the
format specifier (%s) in place of values.
We provide the actual values in the form of tuple in the execute() method of the cursor.
Example
1. import mysql.connector
2. #Create the connection object
1 record inserted!
Insert multiple rows
We can also insert multiple rows at once using the python script. The multiple rows are mentioned as
the list of various tuples.
Each element of the list is treated as one particular row, whereas each element of the tuple is treated
as one particular column value (attribute).
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
3 records inserted!
Row ID
In SQL, a particular row is represented by an insertion id which is known as row id. We can get the
last inserted row id by using the attribute lastrowid of the cursor object.
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
4. #creating the cursor object
5. cur = myconn.cursor()
6.
7. sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s
, %s)"
Python provides the fetchall() method returns the data stored inside the table in the form of rows. We
can iterate the result to get the individual rows.
In this section of the tutorial, we will extract the data from the database by using the python script.
We will also format the output to print it on the console.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
1.9M
58
FOUR almighty pillars of OOP that can improve your PHP skills (from procedural to basics of
OOP)
('John', 101, 25000.0, 201, 'Newyork')
('John', 102, 25000.0, 201, 'Newyork')
('David', 103, 25000.0, 202, 'Port of spain')
('Nick', 104, 90000.0, 201, 'Newyork')
('Mike', 105, 28000.0, 202, 'Guyana')
We can read the specific columns by mentioning their names instead of using star (*).
In the following example, we will read the name, id, and salary from the Employee table and print it
on the console.
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",databas
e = "PythonDB")
4. #creating the cursor object
The fetchone() method is used to fetch only one row from the table. The fetchone() method returns
the next row of the result-set.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
We can format the result by iterating over the result produced by the fetchall() or fetchone() method
of cursor object since the result exists as the tuple object which is not readable.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10.
11. #Reading the Employee data
12. cur.execute("select name, id, salary from Employee")
13.
Name id Salary
John 101 25000
John 102 25000
David 103 25000
Nick 104 90000
Mike 105 28000
We can restrict the result produced by the select statement by using the where clause. This will extract
only those columns which satisfy the where condition.
Name id Salary
John 101 25000
John 102 25000
Example: printing the names with id = 101, 102, and 103
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Reading the Employee data
11. cur.execute("select name, id, salary from Employee where id in (101,102,103)")
12.
13. #fetching the rows from the cursor object
14. result = cur.fetchall()
15.
16. print("Name id Salary");
17.
18. for row in result:
Name id Salary
John 101 25000
John 102 25000
David 103 2500
The ORDER BY clause is used to order the result. Consider the following example.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Reading the Employee data
11. cur.execute("select name, id, salary from Employee order by name")
12.
13. #fetching the rows from the cursor object
14. result = cur.fetchall()
15.
16. print("Name id Salary");
17.
18. for row in result:
19. print("%s %d %d"%(row[0],row[1],row[2]))
20. except:
Name id Salary
David 103 25000
John 101 25000
John 102 25000
Mike 105 28000
Nick 104 90000
Order by DESC
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Reading the Employee data
11. cur.execute("select name, id, salary from Employee order by name desc")
12.
13. #fetching the rows from the cursor object
14. result = cur.fetchall()
15.
16. #printing the result
17. print("Name id Salary");
18. for row in result:
19. print("%s %d %d"%(row[0],row[1],row[2]))
20.
Name id Salary
Nick 104 90000
Mike 105 28000
John 101 25000
John 102 25000
David 103 25000
Update Operation
The UPDATE-SET statement is used to update any column inside the table. The following SQL query
is used to update a column.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #updating the name of the employee whose id is 110
11. cur.execute("update Employee set name = 'alex' where id = 110")
12. myconn.commit()
13. except:
14.
15. myconn.rollback()
16.
17. myconn.close()
The DELETE FROM statement is used to delete a specific record from the table. Here, we must
impose a condition using WHERE clause otherwise all the records from the table will be removed.
The following SQL query is used to delete the employee detail whose id is 110 from the table.
x
1. > delete from Employee where id = 110
Consider the following example.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",data
base = "PythonDB")
5.
6. #creating the cursor object
7. cur = myconn.cursor()
8.
9. try:
10. #Deleting the employee details whose id is 110
11. cur.execute("delete from Employee where id = 110")
12. myconn.commit()
13. except:
14.
15. myconn.rollback()
16.
17. myconn.close()
******