SQL Table Operation Using PymySQL
All about Basic Table SQL queries using python programming languages.
- What is SQL?
- All about Table in SQL.
- Database Connection
- Creating a Table in Database Employee
- Inserting Data in Database Employee
- Updating Table
- Deleting Records from Table
- Drop a Table
- Summary
What is SQL?
- SQL is a query language which is used to communicate with a database. It is the standard language for relational database management systems.
- SQL statements are used to perform tasks such as update data on a database, or retrieve data from a database. Some common relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL Server, Access, Ingres, etc.
- SQL programming can be used to perform multiple actions on data such as :
- Query data from a database
- Insert data into a database
- Update data in a database
- Delete data from a database
- Extract data from a database etc.
- There are specific SQL commands which can be used to accomplish almost everything that one needs to do with a database, they are:
- SELECT: To query data from a database.
- INSERT: To insert data into a database.
- UPDATE: To update data in a database.
- DELETE: To delete data from a database.
- CREATE: To create a table in a database.
- DROP: To drop a table in a database.
- ALTER: To alter a table in a database.
All about Table in SQL.
-
A relational database system contains one or more objects called tables. The data or information for the database are stored in these tables. Tables are uniquely identified by their names and are comprised of columns and rows. Columns contain the column name, data type, and any other attributes for the column. Rows contain the records or data for the columns. Here is a sample table called "employee".
-
Before creating a table in a database, you need to create a database, and then create a table in that database. command to create a database is:
- CREATE DATABASE database_name;
-
We have created database called "employee" in Mysql Workbench with following code:
- CREATE DATABASE employee
Database Connection
- To connect to a database employee using python we need a library called pymysql.
import pymysql
dbconnection = pymysql.connect(host="localhost",user= "root",password= "@sadhguru123",database= "employee")
dbconnection
Creating a Table in Database Employee
- Enter the keywords create table followed by the table name,
- Followed by an open parenthesis,
- Followed by the first column name,
- Eollowed by the data type for that column,
- Followed by any optional constraints, and followed by a closing parenthesis.
-
To create a table in a database, we need to use the following command:
- CREATE TABLE table_name (column_name data_type, column_name data_type, ...);
-
Table name and column name must start with a letter, and can be followed by letters, numbers, or underscores.
- Do not use any SQL reserved keywords as names for tables or column names (such as "select", "create", "insert", etc).
- Data types specify what the type of data can be for that particular column. If a column called "Last_Name", is to be used to hold names, then that particular column should have a "varchar" (variable-length character) data type.
with dbconnection:
with dbconnection.cursor() as cursor:
#Create Table
sql = """CREATE TABLE emp (EmployeeName VARCHAR(20) COLLATE utf8_bin NOT NULL,
EmployeeID INT(6) NOT NULL,
ManagerName VARCHAR(20) COLLATE utf8_bin NOT NULL,
Division INT(1) NOT NULL)"""
cursor.execute(sql)
Inserting Data in Database Employee
- To insert records into a table, enter the key words insert into followed by the table name, followed by an open parenthesis, followed by a list of column names separated by commas, followed by a closing parenthesis, followed by the keyword values, followed by the list of values enclosed in parenthesis.
- The values that you enter will be held in the rows and they will match up with the column names that you specify.
- Strings should be enclosed in single quotes, and numbers should not.
-
To insert data into a table, we need to use the following command:
- INSERT INTO table_name (column_name, column_name, ...) VALUES (value, value, ...);
-
Example:
- INSERT INTO empinfo (first, last, id, age, city, state) VALUES ('Luke', 'Duke', 45454, '22', 'Hazard Co', 'Georgia');
with dbconnection:
with dbconnection.cursor() as cursor:
sql = """INSERT INTO emp5 (EmployeeName,EmployeeID,ManagerName,Division)
VALUES ('Dipesh Silwal','1234', 'Bikash Mallik','1'),
('Mukesh Silwal', '1123', 'Bikash Masslik', '0'),
('Rita khadka', '1122', 'Ramesh Bista', '0')"""
cursor.execute(sql)
# the connection is not autocommited by default. So we must commit to save our changes.
dbconnection.commit()
number_of_rows= cursor.execute("""SELECT * FROM emp5""")
rows = cursor.fetchall()
for row in rows:
print (row)
Updating Table
- The update statement is used to update or change records that match a specified criteria. This is accomplished by carefully constructing a where clause.
- Command to Update a table:
- UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
- Example :
- UPDATA emp SET EmployeeName = 'Rakesh Thapa', 'ManagerName = 'Kedar Bista'' WHERE Division = 0;'
with dbconnection:
with dbconnection.cursor() as cursor:
sql = """UPDATE emp5 SET EmployeeName = 'Rakesh Thapa', ManagerName = 'Kedar Bista' WHERE EmployeeID = '1122'"""
cursor.execute(sql)
dbconnection.commit()
number_of_rows= cursor.execute("""SELECT * FROM emp5""")
rows = cursor.fetchall()
for row in rows:
print (row)
with dbconnection:
with dbconnection.cursor() as cursor:
sql = """DELETE FROM emp5 WHERE EmployeeID = 1122"""
cursor.execute(sql)
dbconnection.commit()
number_of_rows= cursor.execute("""SELECT * FROM emp5""")
rows = cursor.fetchall()
for row in rows:
print (row)
Drop a Table
- The drop table command is used to delete a table and all rows in the table.
- To delete an entire table including all of its rows, issue the drop table command followed by the tablename.
- Drop table is different from deleting all of the records in the table.
- Deleting all of the records in the table leaves the table including column and constraint information.
- Dropping the table removes the table definition as well as all of its rows.
- Command to drop a table:
- DROP TABLE table_name;
- Example:
- DROP TABLE emp5;
with dbconnection:
with dbconnection.cursor() as cursor:
sql = """DROP TABLE emp5"""
cursor.execute(sql)
dbconnection.commit()
number_of_rows= cursor.execute("""SELECT * FROM emp5""")
rows = cursor.fetchall()
for row in rows:
print (row)