This document discusses using Python to interact with SQLite databases. It provides examples of how to connect to an SQLite database, create tables, insert/update/delete records, and query the database. Key points covered include using the sqlite3 module to connect to a database, getting a cursor object to execute SQL statements, and various cursor methods like execute(), executemany(), fetchone(), fetchall(), commit(), and close(). Example code is given for common SQLite operations like creating a table, inserting records, updating records, deleting records, and selecting records.
The document discusses various CRUD (create, read, update, delete) operations in SQLite using Python. It covers creating a database and table, inserting, retrieving, updating, and deleting data from the table. Code examples and explanations are provided for each operation. Key methods for SQLite in Python like connect(), execute(), commit(), close() are also explained.
DEF CON 27 -OMER GULL - select code execution from using sq liteFelipe Prado
The document discusses gaining code execution using SQLite database queries. It provides background on SQLite, examines its attack surface when querying an untrusted database, and explores previous work exploiting memory corruptions. The author proposes a technique called "Query Oriented Programming" to leverage SQL queries to implement memory leakage and other exploitation primitives to achieve remote code execution without using traditional scripting languages.
The sqlite3 module allows Python to interact with SQLite databases. It can connect to a database, execute SQL statements like CREATE, INSERT, UPDATE and DELETE, and fetch the results. The cursor object is used to execute SQL and manage results. Connecting to the database returns a Connection object, and calling cursor() on that returns a Cursor object used to execute statements and queries. Changes are committed using conn.commit() and resources are closed with cursor.close() and conn.close().
The document provides information on how to connect Python to MySQL and perform various operations like creating databases and tables, inserting, updating, deleting and fetching data. It explains how to install the required Python MySQL connector library and connect to a MySQL server from Python. It then demonstrates commands to create databases and tables, insert, update and delete data, and fetch data using where, order by and limit clauses. It also shows how to drop tables and databases and alter table structures.
The Ring programming language version 1.3 book - Part 83 of 88Mahmoud Samir Fayed
This document provides examples and explanations for common questions about using Ring programming language. It demonstrates how to summarize uninitialized variables, print lists containing objects, insert items into lists, print new lines and characters, create GUI applications using Qt, work with modal windows, and connect to SQLite and other databases using ODBC. Various functions, classes and concepts in Ring like Try/Catch, NULL, ISNULL(), lists, Qt classes and ODBC are explained through code examples.
The Ring programming language version 1.8 book - Part 34 of 202Mahmoud Samir Fayed
This document provides documentation on Ring programming language functions for working with MySQL and SQLite databases. It describes functions for connecting to and interacting with databases, including executing queries, retrieving and printing results, and getting metadata. Examples are given showing how to create tables, insert data, retrieve and display results, and close connections. Transaction management functions are also documented.
The Ring programming language version 1.4.1 book - Part 8 of 31Mahmoud Samir Fayed
The document discusses various hashing and encryption functions available in the Ring programming language for security purposes. It describes functions like MD5(), SHA1(), SHA256(), SHA512() etc to calculate hashes of strings. It also discusses the Encrypt() and Decrypt() functions for encrypting and decrypting data along with the Randbytes() function for generating random bytes. Functions from the internetlib library like Download() and SendEmail() are also mentioned. Examples are provided to demonstrate calculating hashes of strings using different hashing algorithms.
SQLite is an embedded SQL database that contains a C library. It is not a client-server database and instead embeds directly into the end program. SQLite follows PostgreSQL syntax. To connect with SQLite from Python, you import the sqlite3 module and use the connect() method to create a Connection object. From there you can create a Cursor object to execute SQL statements like CREATE TABLE, INSERT, SELECT, WHERE, ORDER BY, UPDATE, and DELETE.
The Ring programming language version 1.6 book - Part 46 of 189Mahmoud Samir Fayed
This document summarizes code from the Ring documentation related to user registration, login, and database classes. It describes classes for users, models, views, controllers, and languages that allow for user registration, login, form views, and routing. It also summarizes the Database, ModelBase, and ControllerBase classes that provide functionality for connecting to databases, executing queries, and managing model data.
The Ring programming language version 1.5.3 book - Part 54 of 184Mahmoud Samir Fayed
The document discusses Ring code for database and web application classes and functions. It includes classes for Database, ModelBase, ControllerBase, and View classes. ModelBase handles database operations like insert, update, delete. ControllerBase handles routing and common functions. WebLib contains functions for loading variables, creating pages, encoding special characters, and templating.
The Ring programming language version 1.5.3 book - Part 44 of 184Mahmoud Samir Fayed
This document provides code examples for classes used in a web application framework in Ring. It includes the Database, ModelBase, and ControllerBase classes which handle database connectivity and operations. It also includes an overview of the WebLib API which provides functions and classes for generating HTML pages and elements. Some key classes described are Page, Form, Table, and classes to generate specific HTML elements like Div, Link, Image etc.
This document provides instructions for interfacing Python with MySQL. It discusses installing the MySQL connector library in Python, connecting to a MySQL database, executing queries to retrieve and manipulate data, and performing CRUD (create, read, update, delete) operations. Key steps include importing the MySQL connector, opening a connection, creating a cursor to execute queries, fetching data from the result set, and committing changes to the database. Examples are provided for selecting, inserting, updating, and deleting data as well as creating databases and tables.
This document discusses how to connect a Python script to a MySQL database using the mysql.connector library. It provides steps to establish a connection, create a cursor object, execute SQL queries, fetch data from the cursor, close the connection, and use parameterized queries for inserting, updating, and selecting data from the database.
This document provides an overview of how to access a database in Java using JDBC. It discusses getting a connection to the database, creating statements to execute SQL commands, and using result sets to access query results. It also covers key concepts like prepared statements to prevent SQL injection, design patterns used in JDBC like the factory and iterator patterns, and options for object relational mapping frameworks.
The Ring programming language version 1.6 book - Part 31 of 189Mahmoud Samir Fayed
This document provides documentation on Ring programming language functions for working with SQLite databases. It includes functions for initializing a SQLite object, opening a database, executing SQL statements, closing the database connection, and an example showing how to create a database, insert records, and retrieve data.
The Ring programming language version 1.5.2 book - Part 29 of 181Mahmoud Samir Fayed
The document discusses object-oriented programming in Ring. It shows how to define classes and create objects. Classes contain attributes and methods, and objects are instances of classes that can access attributes and call methods using braces or dot notation. Default values can be set for class attributes. Printing, inheritance, private members, and other OOP concepts are also covered.
The Ring programming language version 1.7 book - Part 48 of 196Mahmoud Samir Fayed
This document provides code examples and documentation for Ring's web library (weblib.ring). It describes classes and methods for generating HTML pages, forms, tables and other elements. This includes the Page class for adding common elements like text, headings, paragraphs etc., the Application class for handling requests, cookies and encoding, and classes representing various HTML elements like forms, inputs, images etc. It also provides an overview of how to create pages dynamically using View and Controller classes along with Model classes for database access.
The Python DB-API standard supports connecting to and interacting with many database servers like MySQL, PostgreSQL, and Oracle. To access a database, a Python module like MySQLdb must be installed. Code examples demonstrate how to connect to a MySQL database, create tables, insert/update/delete records, and handle errors according to the DB-API. Transactions ensure data integrity using atomicity, consistency, isolation, and durability properties.
This document discusses SQL injection attacks and how to mitigate them. It begins by explaining how injection attacks work by tricking applications into executing unintended commands. It then provides examples of how SQL injection can be used to conduct unauthorized access and data modification attacks. The document discusses techniques for finding and exploiting SQL injection vulnerabilities, including through the SELECT, INSERT, UPDATE and UNION commands. It also covers ways to mitigate injection attacks, such as using prepared statements with bound parameters instead of concatenating strings.
The Ring programming language version 1.5 book - Part 8 of 31Mahmoud Samir Fayed
This document summarizes key classes and methods from the Ring web library (weblib.ring).
The Application class contains methods for encoding, decoding, cookies, and more. The Page class contains methods for generating common HTML elements and structures. Model classes like UsersModel manage data access and object relational mapping. Controller classes handle requests and coordinate the view and model.
The Ring programming language version 1.8 book - Part 34 of 202Mahmoud Samir Fayed
This document provides documentation on Ring programming language functions for working with MySQL and SQLite databases. It describes functions for connecting to and interacting with databases, including executing queries, retrieving and printing results, and getting metadata. Examples are given showing how to create tables, insert data, retrieve and display results, and close connections. Transaction management functions are also documented.
The Ring programming language version 1.4.1 book - Part 8 of 31Mahmoud Samir Fayed
The document discusses various hashing and encryption functions available in the Ring programming language for security purposes. It describes functions like MD5(), SHA1(), SHA256(), SHA512() etc to calculate hashes of strings. It also discusses the Encrypt() and Decrypt() functions for encrypting and decrypting data along with the Randbytes() function for generating random bytes. Functions from the internetlib library like Download() and SendEmail() are also mentioned. Examples are provided to demonstrate calculating hashes of strings using different hashing algorithms.
SQLite is an embedded SQL database that contains a C library. It is not a client-server database and instead embeds directly into the end program. SQLite follows PostgreSQL syntax. To connect with SQLite from Python, you import the sqlite3 module and use the connect() method to create a Connection object. From there you can create a Cursor object to execute SQL statements like CREATE TABLE, INSERT, SELECT, WHERE, ORDER BY, UPDATE, and DELETE.
The Ring programming language version 1.6 book - Part 46 of 189Mahmoud Samir Fayed
This document summarizes code from the Ring documentation related to user registration, login, and database classes. It describes classes for users, models, views, controllers, and languages that allow for user registration, login, form views, and routing. It also summarizes the Database, ModelBase, and ControllerBase classes that provide functionality for connecting to databases, executing queries, and managing model data.
The Ring programming language version 1.5.3 book - Part 54 of 184Mahmoud Samir Fayed
The document discusses Ring code for database and web application classes and functions. It includes classes for Database, ModelBase, ControllerBase, and View classes. ModelBase handles database operations like insert, update, delete. ControllerBase handles routing and common functions. WebLib contains functions for loading variables, creating pages, encoding special characters, and templating.
The Ring programming language version 1.5.3 book - Part 44 of 184Mahmoud Samir Fayed
This document provides code examples for classes used in a web application framework in Ring. It includes the Database, ModelBase, and ControllerBase classes which handle database connectivity and operations. It also includes an overview of the WebLib API which provides functions and classes for generating HTML pages and elements. Some key classes described are Page, Form, Table, and classes to generate specific HTML elements like Div, Link, Image etc.
This document provides instructions for interfacing Python with MySQL. It discusses installing the MySQL connector library in Python, connecting to a MySQL database, executing queries to retrieve and manipulate data, and performing CRUD (create, read, update, delete) operations. Key steps include importing the MySQL connector, opening a connection, creating a cursor to execute queries, fetching data from the result set, and committing changes to the database. Examples are provided for selecting, inserting, updating, and deleting data as well as creating databases and tables.
This document discusses how to connect a Python script to a MySQL database using the mysql.connector library. It provides steps to establish a connection, create a cursor object, execute SQL queries, fetch data from the cursor, close the connection, and use parameterized queries for inserting, updating, and selecting data from the database.
This document provides an overview of how to access a database in Java using JDBC. It discusses getting a connection to the database, creating statements to execute SQL commands, and using result sets to access query results. It also covers key concepts like prepared statements to prevent SQL injection, design patterns used in JDBC like the factory and iterator patterns, and options for object relational mapping frameworks.
The Ring programming language version 1.6 book - Part 31 of 189Mahmoud Samir Fayed
This document provides documentation on Ring programming language functions for working with SQLite databases. It includes functions for initializing a SQLite object, opening a database, executing SQL statements, closing the database connection, and an example showing how to create a database, insert records, and retrieve data.
The Ring programming language version 1.5.2 book - Part 29 of 181Mahmoud Samir Fayed
The document discusses object-oriented programming in Ring. It shows how to define classes and create objects. Classes contain attributes and methods, and objects are instances of classes that can access attributes and call methods using braces or dot notation. Default values can be set for class attributes. Printing, inheritance, private members, and other OOP concepts are also covered.
The Ring programming language version 1.7 book - Part 48 of 196Mahmoud Samir Fayed
This document provides code examples and documentation for Ring's web library (weblib.ring). It describes classes and methods for generating HTML pages, forms, tables and other elements. This includes the Page class for adding common elements like text, headings, paragraphs etc., the Application class for handling requests, cookies and encoding, and classes representing various HTML elements like forms, inputs, images etc. It also provides an overview of how to create pages dynamically using View and Controller classes along with Model classes for database access.
The Python DB-API standard supports connecting to and interacting with many database servers like MySQL, PostgreSQL, and Oracle. To access a database, a Python module like MySQLdb must be installed. Code examples demonstrate how to connect to a MySQL database, create tables, insert/update/delete records, and handle errors according to the DB-API. Transactions ensure data integrity using atomicity, consistency, isolation, and durability properties.
This document discusses SQL injection attacks and how to mitigate them. It begins by explaining how injection attacks work by tricking applications into executing unintended commands. It then provides examples of how SQL injection can be used to conduct unauthorized access and data modification attacks. The document discusses techniques for finding and exploiting SQL injection vulnerabilities, including through the SELECT, INSERT, UPDATE and UNION commands. It also covers ways to mitigate injection attacks, such as using prepared statements with bound parameters instead of concatenating strings.
The Ring programming language version 1.5 book - Part 8 of 31Mahmoud Samir Fayed
This document summarizes key classes and methods from the Ring web library (weblib.ring).
The Application class contains methods for encoding, decoding, cookies, and more. The Page class contains methods for generating common HTML elements and structures. Model classes like UsersModel manage data access and object relational mapping. Controller classes handle requests and coordinate the view and model.
ELectronics Boards & Product Testing_Shiju.pdfShiju Jacob
This presentation provides a high level insight about DFT analysis and test coverage calculation, finalizing test strategy, and types of tests at different levels of the product.
The Fluke 925 is a vane anemometer, a handheld device designed to measure wind speed, air flow (volume), and temperature. It features a separate sensor and display unit, allowing greater flexibility and ease of use in tight or hard-to-reach spaces. The Fluke 925 is particularly suitable for HVAC (heating, ventilation, and air conditioning) maintenance in both residential and commercial buildings, offering a durable and cost-effective solution for routine airflow diagnostics.
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxRishavKumar530754
LiDAR-Based System for Autonomous Cars
Autonomous Driving with LiDAR Tech
LiDAR Integration in Self-Driving Cars
Self-Driving Vehicles Using LiDAR
LiDAR Mapping for Driverless Cars
Data Structures_Linear data structures Linked Lists.pptxRushaliDeshmukh2
Concept of Linear Data Structures, Array as an ADT, Merging of two arrays, Storage
Representation, Linear list – singly linked list implementation, insertion, deletion and searching operations on linear list, circularly linked lists- Operations for Circularly linked lists, doubly linked
list implementation, insertion, deletion and searching operations, applications of linked lists.
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfMohamedAbdelkader115
Glad to be one of only 14 members inside Kuwait to hold this credential.
Please check the members inside kuwait from this link:
https://www.rics.org/networking/find-a-member.html?firstname=&lastname=&town=&country=Kuwait&member_grade=(AssocRICS)&expert_witness=&accrediation=&page=1
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYijscai
With the increased use of Artificial Intelligence (AI) in malware analysis there is also an increased need to
understand the decisions models make when identifying malicious artifacts. Explainable AI (XAI) becomes
the answer to interpreting the decision-making process that AI malware analysis models use to determine
malicious benign samples to gain trust that in a production environment, the system is able to catch
malware. With any cyber innovation brings a new set of challenges and literature soon came out about XAI
as a new attack vector. Adversarial XAI (AdvXAI) is a relatively new concept but with AI applications in
many sectors, it is crucial to quickly respond to the attack surface that it creates. This paper seeks to
conceptualize a theoretical framework focused on addressing AdvXAI in malware analysis in an effort to
balance explainability with security. Following this framework, designing a machine with an AI malware
detection and analysis model will ensure that it can effectively analyze malware, explain how it came to its
decision, and be built securely to avoid adversarial attacks and manipulations. The framework focuses on
choosing malware datasets to train the model, choosing the AI model, choosing an XAI technique,
implementing AdvXAI defensive measures, and continually evaluating the model. This framework will
significantly contribute to automated malware detection and XAI efforts allowing for secure systems that
are resilient to adversarial attacks.
Fluid mechanics is the branch of physics concerned with the mechanics of fluids (liquids, gases, and plasmas) and the forces on them. Originally applied to water (hydromechanics), it found applications in a wide range of disciplines, including mechanical, aerospace, civil, chemical, and biomedical engineering, as well as geophysics, oceanography, meteorology, astrophysics, and biology.
It can be divided into fluid statics, the study of various fluids at rest, and fluid dynamics.
Fluid statics, also known as hydrostatics, is the study of fluids at rest, specifically when there's no relative motion between fluid particles. It focuses on the conditions under which fluids are in stable equilibrium and doesn't involve fluid motion.
Fluid kinematics is the branch of fluid mechanics that focuses on describing and analyzing the motion of fluids, such as liquids and gases, without considering the forces that cause the motion. It deals with the geometrical and temporal aspects of fluid flow, including velocity and acceleration. Fluid dynamics, on the other hand, considers the forces acting on the fluid.
Fluid dynamics is the study of the effect of forces on fluid motion. It is a branch of continuum mechanics, a subject which models matter without using the information that it is made out of atoms; that is, it models matter from a macroscopic viewpoint rather than from microscopic.
Fluid mechanics, especially fluid dynamics, is an active field of research, typically mathematically complex. Many problems are partly or wholly unsolved and are best addressed by numerical methods, typically using computers. A modern discipline, called computational fluid dynamics (CFD), is devoted to this approach. Particle image velocimetry, an experimental method for visualizing and analyzing fluid flow, also takes advantage of the highly visual nature of fluid flow.
Fundamentally, every fluid mechanical system is assumed to obey the basic laws :
Conservation of mass
Conservation of energy
Conservation of momentum
The continuum assumption
For example, the assumption that mass is conserved means that for any fixed control volume (for example, a spherical volume)—enclosed by a control surface—the rate of change of the mass contained in that volume is equal to the rate at which mass is passing through the surface from outside to inside, minus the rate at which mass is passing from inside to outside. This can be expressed as an equation in integral form over the control volume.
The continuum assumption is an idealization of continuum mechanics under which fluids can be treated as continuous, even though, on a microscopic scale, they are composed of molecules. Under the continuum assumption, macroscopic (observed/measurable) properties such as density, pressure, temperature, and bulk velocity are taken to be well-defined at "infinitesimal" volume elements—small in comparison to the characteristic length scale of the system, but large in comparison to molecular length scale
2. IMPORTING MODULE
• “Import” statement imports the sqlite3 module in the program.
• Using the classes and methods defined in the sqlite3 module we can communicate with the
SQLite database.
• Import in python is similar to #include header_file in C/C++.
• Python modules can get access to code from another module by importing the file/function
using import.
• When the import is used, it searches for the module initially in the local scope by calling
__import__() function.
import module_name
3. IMPORTING MODULE
• For example:
import math
print(math.pi)
import module_name.member_name
• In the above code module, math is imported, and its variables can be accessed by considering
it to be a class and pi as its object.
• The value of pi is returned by __import__().
• pi as a whole can be imported into our initial code, rather than importing the whole module.
4. IMPORTING MODULE
• For example:
from math import pi
# Note that in the above example,
# we used math.pi. Here we have used
# pi directly.
print(pi)
from module_name import *
• In the above code module, math is not imported, rather just pi has been imported as a variable.
• All the functions and constants can be imported using *.
5. CONNECT() AND EXECUTE()
• Connecting to the SQLite Database can be established using the connect() method, passing the
name of the database to be accessed as a parameter.
• If that database does not exist, then it’ll be created.
sqliteConnection = sqlite3.connect('sql.db')
• But what if you want to execute some queries after the connection is being made.
• For that, a cursor has to be created using the cursor() method on the connection instance,
which will execute our SQL queries.
cursor = sqliteConnection.cursor()
print('DB Init')
6. CONNECT() AND EXECUTE()
• The SQL query to be executed can be written in form of a string, and then executed by calling
the execute() method on the cursor object.
• Then, the result can be fetched from the server by using the fetchall() method, which in this
case, is the SQLite Version Number.
query = 'SQL query;'
cursor.execute(query)
result = cursor.fetchall()
print('SQLite Version is {}'.format(result))
7. FETCHALL( ) & FETCHONE( )
• fetchall(), fetchmany(), and fetchone( ) to retrieve data from MySQL, PostgreSQL, SQLite
database.
• cursor.fetchall() fetches all the rows of a query result. It returns all the rows as a list of tuples.
An empty list is returned if there is no record to fetch.
• cursor.fetchmany(size) returns the number of rows specified by size argument. When called
repeatedly, this method fetches the next set of rows of a query result and returns a list of
tuples. If no more rows are available, it returns an empty list.
• cursor.fetchone() method returns a single record or None if no more rows are available.
8. FETCHALL( )
To fetch all rows from a database table, you need to follow these simple steps: –
• Create a database Connection from Python.
• Define the SELECT query. Here you need to know the table and its column details.
• Execute the SELECT query using the cursor.execute() method.
• Get resultSet (all rows) from the cursor object using a cursor.fetchall().
• Iterate over the ResultSet using for loop and get column values of each row.
• Close the Python database connection.
• Catch any SQL exceptions that may come up during the process.
9. FETCHALL( )
import sqlite3
def getAllRows():
try:
connection = sqlite3.connect('SQLite_Python.db')
cursor = connection.cursor()
print("Connected to SQLite")
sqlite_select_query = """SELECT * from database_developers"""
cursor.execute(sqlite_select_query)
records = cursor.fetchall()
10. FETCHALL( )
print("Total rows are: ", len(records))
print("Printing each row")
for row in records:
print("Id: ", row[0])
print("Name: ", row[1])
print("Email: ", row[2])
print("Salary: ", row[3])
print("n")
cursor.close()
except sqlite3.Error as error:
print("Failed to read data from table", error)
finally:
if connection:
connection.close()
print("The Sqlite connection is closed")
getAllRows() //function call to get all row
11. FETCHMANY()
• Retrieve a few rows from a table.
• Here size is the number of rows to be retrieved.
• This method fetches the next set of rows of a query result and returns a list of tuples. If no
more rows are available, it returns an empty list.
• Cursor’s fetchmany() method returns the number of rows specified by size argument. Default
value is 1. If the specified size is 100, then it returns 100 rows.
• Let try to fetch 3 rows from table using a cursor.fetchmany(size)
rows = cursor.fetchmany([size=cursor.arraysize])
12. FETCHMANY( )
import sqlite3
def getlimitedRows(size):
try:
connection = sqlite3.connect('SQLite_Python.db')
cursor = connection.cursor()
print("Connected to database")
sqlite_select_query = """SELECT * from database_developers"""
cursor.execute(sqlite_select_query)
records = cursor.fetchmany(size)
13. FETCHMANY( )
print("Fetching Total ", size," rows")
print("Printing each row")
for row in records:
print("Id: ", row[0])
print("Name: ", row[1])
print("Email: ", row[2])
print("Salary: ", row[3])
print("n")
cursor.close()
except sqlite3.Error as error:
print("Failed to read data from table", error)
finally:
if (connection):
connection.close()
print("The Sqlite connection is closed")
getlimitedRows(3) // function call to get 3 row
14. FETCHONE()
• Retrieve only single rows from a table.
• It can return a none if no rows are available in the result set.
• cursor.fetchone() increments the cursor position by one and return the next row.
rows = cursor.fetchone( )
15. FETCHONE( )
import sqlite3
def getSingleRows():
try:
connection = sqlite3.connect('SQLite_Python.db')
cursor = connection.cursor()
print("Connected to database")
sqlite_select_query = """SELECT * from database_developers"""
cursor.execute(sqlite_select_query)
print("Fetching single row")
16. FETCHONE( )
record = cursor.fetchone()
print(record)
print("Fetching next row")
record = cursor.fetchone()
print(record)
cursor.close()
except sqlite3.Error as error:
print("Failed to read data from table", error)
finally:
if connection:
connection.close()
print("The Sqlite connection is closed")
getSingleRows() // get single row
17. CRUD OPERATION USING EXECUTE( )
• Retrieve only single rows from a table.
• It can return a none if no rows are available in the result set.
• cursor.fetchone() increments the cursor position by one and return the next row.
rows = cursor.fetchone( )
18. STEPS TO CONNECT WITH SQLITE DATABASE
• Import sqlite3 module.
• Use the connect( ) method.
• Use the cursor( ) method.
• Use the execute( ) method.
• Extract result using fetchall( ).
• Close cursor and connection objects.
• Catch database exception if any that may occur during connection process.
19. CREATE SQLITE TABLE FROM PYTHON
Steps for create a table in SQLite from Python: –
• Connect to SQLite using a sqlite3.connect().
• Prepare a create table query.
• Execute the query using a cursor.execute(query)
20. CREATE SQLITE TABLE FROM PYTHON
import sqlite3
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email text NOT NULL UNIQUE,
joining_date datetime,
salary REAL NOT NULL);'''
21. FETCHONE( )
cursor = sqliteConnection.cursor()
print("Successfully Connected to SQLite")
cursor.execute(sqlite_create_table_query)
sqliteConnection.commit()
print("SQLite table created")
cursor.close()
except sqlite3.Error as error:
print("Error while creating a sqlite table", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("sqlite connection is closed")
22. INSERT OPERATION
• Connect to SQLite from Python
• Define a SQL Insert query
• Get Cursor Object from Connection
• Execute the insert query using execute() method
• Commit your changes
• Get the number of rows affected
• Verify result using the SQL SELECT query
• Close the cursor object and database connection object
24. INSERT
count = cursor.execute(sqlite_insert_query)
sqliteConnection.commit()
print("Record inserted successfully into SqliteDb_developers table ", cursor.rowcount)
cursor.close()
except sqlite3.Error as error:
print("Failed to insert data into sqlite table", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")
25. INSERT OPERATION USING PYTHON VARIABLE
• Sometimes we need to insert a Python variable value into a table’s column.
• This value can be anything, including integer, string, float, and DateTime.
• For example, in the registration form person enter his/her details. You can take those values
in Python variables and insert them into the SQLite table.
• We use a parameterized query to insert Python variables into the table.
• Using a parameterized query, we can pass python variables as a query parameter in which
placeholders (?)
27. INSERT OPERATION USING PYTHON VARIABLE
data_tuple = (id, name, email, joinDate, salary)
cursor.execute(sqlite_insert_with_param, data_tuple)
sqliteConnection.commit()
print("Python Variables inserted successfully into SqliteDb_developers table")
cursor.close()
except sqlite3.Error as error:
print("Failed to insert Python variable into sqlite table", error)
28. INSERT OPERATION USING PYTHON VARIABLE
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")
insertVaribleIntoTable(2, 'Joe', '[email protected]', '2019-05-19', 9000)
insertVaribleIntoTable(3, 'Ben', '[email protected]', '2019-02-23', 9500)
29. INSERT MULTIPLE ROW
• Sometimes we need to insert multiple rows into the table in a single insert query.
• For example, You wanted to add all records from the CSV file into the SQLite table.
• Instead of executing the INSERT query every time to add each record, you can perform a
bulk insert operation in a single query using a cursor’s executemany() function.
• The executemany() method takes two arguments SQL query and records to update.
33. UPDATE
• Most of the time, we need to update a table with some runtime values.
• For example, when users update their profile or any other details through a user interface,
we need to update a table with those new values.
• In such cases, It is always best practice to use a parameterized query.
• The parameterized query uses placeholders (?) inside SQL statements that contain input
from users.
• It helps us to update runtime values and prevent SQL injection concerns.
34. UPDATE
import sqlite3
def updateSqliteTable(id, salary):
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sql_update_query = """Update SqliteDb_developers set salary = ? where id = ?"""
data = (salary, id)
cursor.execute(sql_update_query, data)
36. UPDATE
• We used two placeholders in the update query, one for the salary column and the other is
for the id column.
• Next, We prepared a data tuple by specifying two Python variables in sequential order.
• Next, we passed the SQL update query and data tuple to the cursor.execute() method.
Remember variables order in the tuple is sequential as per column placeholders order.
37. UPDATE MULTIPLE ROW USING CURSOR
• In the above example, we have used execute() method of cursor object to update a single
record. But sometimes, we need to update multiple rows of the SQLite table.
• For example, you want to increase the salary of developers by 20%.
• Instead of executing the UPDATE query every time to update each record, you can perform
bulk update operations in a single query using the cursor.executemany() method.
• The executemany(query, seq_param) method accepts the following two parameters
• SQL query
• list of records to be updated.
38. UPDATE MULTIPLE ROW USING CURSOR
import sqlite3
def updateMultipleRecords(recordList):
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sqlite_update_query = """Update SqliteDb_developers set salary = ? where id = ?"""
cursor.executemany(sqlite_update_query, recordList)
39. UPDATE MULTIPLE ROW USING CURSOR
sqliteConnection.commit()
print("Total", cursor.rowcount, "Records updated
successfully")
sqliteConnection.commit()
cursor.close()
except sqlite3.Error as error:
print("Failed to update multiple records of sqlite table", error)
40. UPDATE MULTIPLE ROW USING CURSOR
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")
records_to_update = [(9700, 4), (7800, 5), (8400, 6)]
updateMultipleRecords(records_to_update)
41. UPDATE MULTIPLE ROW USING CURSOR
• We prepared the SQLite update query with two placeholders (“salary” and “Id” column ) and
a list of records to update in tuple format.
• Each element of a list is nothing but a tuple for each row. Each tuple contains two values, i.e.,
salary and id of a developer.
• We passed SQLite update query and record list to executemany() as arguments.
• To get to know the number of records updated, we used a cursor.rowcount function.
42. DELETE
• In order to delete data in the SQLite database from a Python program, you use the following
steps:
• First, establish a connection the SQLite database by creating a Connection object using the
connect() function.
• Second, to execute a DELETE statement, you need to create a Cursor object using the
cursor() method of the Connection object.
• Third, execute the DELETE statement using the execute() method of the Cursor object. In
case you want to pass the arguments to the statement, you use a question mark (?) for each
argument.
43. EXAMPLE:
#import the module.
import sqlite3;
#Use the connect( ) method for open or create a database
con = sqlite3.connect("MyDB.db")
print("Database Created")
#Use the cursor( ) method using connection object
cur = con.cursor()
#create a table using execute() method
createtbl = "create table test(ID int primary key, name text not null, total int not null)"
con.execute(createtbl)
print("Table Created")
44. INSERT DATA
#insert the data using execute() method
insertquery = "insert into test values(1,'Nidhi',78);"
con.execute(insertquery)
print("data inserted", con.total_changes)
#take input from user to insert data into table.
id1 = input("Enter ID:")
name = input("Enter Name:")
total = input("Enter Total:")
con.execute("insert into test values(?,?,?)", (id1,name,total))
print("data inserted", con.total_changes)
45. INSERT MULTIPLE DATA
#insert multiple data into table using executemany() method.
records = [(3,'mnp',33), (4,'pqr',67),(6,'wxy',88)]
con.executemany("insert into test values(?,?,?)", records)
print("data inserted", con.total_changes)
46. UPDATE DATA
#update the data using execute() method
updatequery = "update test set total=90 where id=1"
con.execute(updatequery)
print("data updated", con.total_changes)
#take input from user to update data into table.
idtoupadte = input("Enter id:")
con.execute("update test set total=99 where id=?", idtoupadte)
print("data updated", con.total_changes)
47. UPDATE DATA
#take multiple input from user to update data.
updatename=input("enter update name:")
updateid = input("enter id:")
con.execute("update test set name=? where id=?",(updatename,updateid))
print("data updated", con.total_changes)
#update multiple data into table using executemany() method.
updatedata = [('priya',55,3),
('payal', 56,4),
('pritam',57,6)]
con.executemany("update test set name=?, total=? where id=?",updatedata)
print("data updated", con.total_changes)
48. DELETE DATA
#delete data from table using execute() method
deletequery = "delete from test where id=1"
con.execute(deletequery)
print("data deleted", con.total_changes)
#take input from user to delete data into table.
deleteid = input("Enter id:")
con.execute("delete from test where id=?",deleteid)
print("data deleted", con.total_changes)
49. SELECT DATA
#select data from table usinf cursor() object and print the data using for loop.
data = con.execute("SELECT * from test")
for row in data:
print ("ID = ", row[0])
print ("NAME = ", row[1])
print ("TOTAL = ", row[2])
50. SELECT DATA- FETCHALL()
#use the fetchall() method to get all data.
cur.execute("select * from test")
data1 = cur.fetchall()
for row in data1:
print ("ID = ", row[0])
print ("NAME = ", row[1])
print ("TOTAL = ", row[2])
51. SELECT DATA- FETCHONE() AND FECTHMANY()
#use fetchone() to get a single record
cur.execute("select * from test")
data2 =cur.fetchone()
print(data2)
#use fetchmany() method to get number of data record
cur.execute("select * from test")
data3 = cur.fetchmany(2)
print(data3)
52. EXAMPLE
#print the list of tables of database
print("List of tables:")
cur.execute("SELECT * FROM sqlite_master WHERE type='table';")
print(cur.fetchall())
#print the structure of a table.
a= con.execute("PRAGMA table_info('test')")
print("nTable structure of test:", a)
for i in a:
print(i)
53. EXAMPLE
#print the foreign keys in database
rows=cur.execute('pragma foreign_keys')
for r in rows:
print (r)
#use commit() method at last to save changes in your table
con.commit()
#use close() method to close the connection
con.close()
54. WHAT IS EXCEPTION?
• An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python object that
represents an error.
• When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.
55. HANDLING AN EXCEPTION?
• If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block. After the try: block, include an
except: statement, followed by a block of code which handles the problem as elegantly as
possible.
56. HANDLING AN EXCEPTION?
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The else block lets you execute code when there is no error.
• The finally block lets you execute code, regardless of the result of the try- and except blocks.
• When an error occurs, or exception as we call it, Python will normally stop and generate an
error message.
• These exceptions can be handled using the try statement:
57. TRY EXCEPT
• This statement will raise an error, because x is not defined:
print(x)
• If we write below statement then it print a error statement rather than throw a error.
try:
print(x)
except:
print("An exception occurred")
Output:
An exception occurred
58. MANY EXCEPTION
• You can define as many exception blocks as you want, e.g. if you want to execute a special block
of code for a special kind of error:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Output:
Variable x is not defined
• Print one message if the try block raises a NameError and another for other errors:
59. ELSE
• You can use the else keyword to define a block of code to be executed if no errors were
raised:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Output:
Hello
Nothing went wrong
60. FINALLY
• The finally block, if specified, will be executed regardless if the try block raises an error or
not. try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Output:
Something went wrong
The 'try except' is finished