Location via proxy:
[ UP ]
[Report a bug]
[Manage cookies]
No cookies
No scripts
No ads
No referrer
Show this form
Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
530 views
Python With SQLITE
Uploaded by
Jenish Gojariya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Python With SQLITE For Later
Download
Save
Save Python With SQLITE For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
530 views
Python With SQLITE
Uploaded by
Jenish Gojariya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Python With SQLITE For Later
Carousel Previous
Carousel Next
Save
Save Python With SQLITE For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 116
Search
Fullscreen
PYTHON WITH SQLITE (euinmens Vivekanend College | _ BCA.B.Con,.8.3,A..B.Ed Library By: Mr. Chetan N. Rathod [M.C.A., M.Phil.] Mr. Mayank N. Jain [M.C.A.] Ms. Bhumika K. Charnanand [M.C.A., M.Phil.] National Level Publication Ary Jurmp2Learn-Publicationat ne ena enna INDEX UNIT-1 | Introduction to SQLite 1 SQlite History 2 Differences between SQL and SQLite 3 |__| install SQLite on Windows 3 SQlite Features 5 SQlite Advantages 5 SQlite Disadvantages 7 SQLite Commands 7 Data Definifion Language 7 Data Manipulation language 7 Data Query Language 8 SQlite data types 8 SQlite Storage Classes 8 ‘SQLite Affinity Type 9 ‘SQLite manifest typing & type affinity 9 SQlife — Transactions 10 — Properties of Transactions 10 BEGIN TRANSACTION Command 7 SQlite COMMIT Command V1 SQlite ROLLBACK Command 12 Dala Filtering 12 SQlife DISTINCT Clause 12 ‘SQLite WHERE Clause 4 SQlife BETWEEN Clause 15 SQlite IN Clause 16 SQlife NOTIN Clause 1 SQlife LIKE Clause 7SQlite - UNION Clause 18 SQlite intersect Clause 9 r SQlite Except 20 [- SQlite LIMIT Clause 21 SQlite GROUP BY Clause 22 SQlite HAVING Clause 3 SQlite CASE 23 ‘SQlite joins 7 25 | SQlife inner Join ~ 25 ‘SQlite Outer Join 25 SQlite Leff Outer Join oS 26 The CROSS JOIN 26 SQlite Trigger 27 Usage of triggers 7 ‘Advantages of using triggers 2 SQlite CREATE TRIGGER 28 SQLite DROP TRIGGER: 30° Exercise 30 UNIT-2 | Database backup and CSV handing 31 SQlite dump 32 Dump the enfire database into a file 32 Dump a specific table using the dump command | __32, Dump tables structure 33 Dump data of one or more fables into a file Eg 2.2 CSV files handling 34 Import a CSV file into a table = 34 Export a CSV file from table 3% Exercise a PittaUNIT-3 | Python interaction wiia SQLite 9 Module 40 Create a Module 40 7 Loading the module 40 The import statement 40 The from-import statement a PYTHONPATH 42 Concepts of Namespace 44 Scope of Namespace 45 Packages in Python 46 Importing sqlite3 module a7 connect}, executel) fetchone() and fetchall() a Create a Table using python 50 insert Records, Select Records and Delete Records 31 commiti) 38 Exercise 54 UNIT-4 | Python interaction with SQlite 35 Opening a file 56 , close{) method 8 Reading and Writing Files 58 The with statement 60 CSV module ai Open a CSV File i csv reader(), csv.writer(), Writerows(), 62 DictReader(), DictWriter{) Close a CSV File 68 Dafaframe Handling using Panda and Numpy 8 Python Pandas library 8 Series 8Exercise - DataFrame - 70 [ ‘Operation on Dataframe 73 head, tail, loc, iloc, value, 74 to_numpy(), describe() Performing Queries on Data 81 | Sorting the Data 7 81 Handing Missing Data - 82 [ Python NumPy 83 NomPyEnvirenmentSetup 84 NumPy Ndarray 85 Numpy Methods : mean, median, mode. 87 | variance, Standard Deviation Exercise 92 UNIT - 5 Data Visualization using data frame 93 Data Visualization 94 | ‘Maiplotlib Python Libraries - 94 install matplotlib 94 | Maiplotiib.pyplot.legend() 9 ~ Subplotis - 98 Scaifer Plot in Matplotiis — | Line chart in Matplotiib 100 Plot multiple lines in a single chart or | Plot Histogram in Maiplotis 102 Bar Plot in Maiplotlib 105 , | Pie chart in Matplotlib 106 Save Plot as a File 107 110 |Ty Unit- 1 Introduction to SQLite 1 Unit - 1 Introduction to SQLite Jump2Learn Publication {www.jump2learn.com]Unit- 1 Introduction to SQLite INTRODUCTION = satite is embedded relational database management system. It Is self contained, serverless, zero configuration and transactional SQL database engine, «SAtite is free to use for any purpose commercial or private, In other words, ‘sqlite is an open source, zero-configuration, self-contained, stand alone, transaction relational database engine designed to be embedded into an application”, + sQtite is different from other SQL databases because unlike most other SQL databases, SQLite does not have a separate server process, «treads and writes directly to ordinary disk files. A complete SQL database with multiple tables, indices, triggers, and views, is contained in a single disk ile « SQlite is written in ANSI-C and provides simple and easy-to-use API « satite is available on UNIX (Linux, Mac 0S-X, Android, 105) and Windows (Win32, WinCE, WinRT). SQLite History SQtite was designed originally on August 2000. It is named SQLite because it Is very light weight (less than 500Kb size) unlike other database management systems like SQL Server or Oracle. «2000 - D. Richard Hipp designed SQLite for the purpose of no administration required for operating a program. «2000 - In August, SQLite 1.0 released with GNU Database Manager. «2011 - Hipp announced to add UNQI interface to SQLite DB and to develop UNALite (Document oriented database) Jump2Learn Publication [www.jump2learn.com] eset once ————_—rr cr cnerescnemeenenen et ate Unit- 1 Introduction to SQLite Differences between SQL and SQLite sal Tals Salite + SQLisa Structured Query Language used to query a Relational Database System. It is written in = language. SQLite is an Embeddable Relational Database Management System which is written in ANSI-C. © SQL is a standard which specifies how a relational schema is created, data is inserted or updated in the relations, transactions are started and stopped, etc. SQLite is file-based. It is different from other SQL databases because unlike most other SQL databases, SQlite does not have a separate © Main-components of SQL are Data Definition Language(DDL) , Data Manipulation —_Language(DML), Embedded SQL and Dynamic SQL. server process. n ‘SQLite supports many features of SQI and has high performance and does not support stored procedures. + SQL is Structured Query Language which is used with databases like MySQL, Oracle, Microsoft SQL Server, IBM DB2, etc. It is not a database itself. SQlite is a portable database resource. You have to get an extension of SQlite in whatever language you are programming in to access that database, You can access all of the desktop and mobile applications. * Aconventional SQl database needs to be running as a service like OracleDB to connect to and provide a lot of functionalities SQlite database system doesn’t provide such functionalities. © SQL is a query language which is used by different SQL databases. It is not a database itself. , SQlite is a database management system itself which uses SQL. Install SQLite on Windows First, go to the https://www-sqlite.org website. + Step 1- Go tosdtite download page, “Download link https://www.salite.org/download.html ” and download precompiled binaries from Windows section. Jump2tearn Publication [www.jump2learn.com]Unit- 4 Introduction to SQLite recoiled Binaries for Windows gi ROL Site vesion 3.355, sttetvlewina a tude of cond nea or mann Se tse es, cdg he comma it hl ewan, es Soran, andthe pram, (81 mB) + Step 2 Download salte-shell-win32-*.2ip and sqlite-dll-win32-*.zip zipped files + Step 3~ Create a folder C:\psalite and unzip above two zipped files in this folder, which will give you salite3.def, sqlite3.dll and sqlite3.exe files [Esqiditfxe ([Bsqite.ere [Bisqlte3_analyzerere + Step 4~ Add C:\>sqlite in your PATH environment variable and finally go to the command prompt and issue sqlite3 command, which should display the following result Open the command line window, and navigate to the C:\sqlite folder. Now type sqlite3 and press enter, you should see the following output help command from the sqlte> prompt to see all available commands in salite3 quit the sqlite>, you use .quit command. Jump2Learn Publication (www jump2learn.com]j rere in aetna Unit- 1 Introduction to SQLite 5 SQLite Features SQLite is totally free: SQLite is open-source. So, no license is required to work with it SQlite is server less: SQLite doesn't require a different server process or system to operate. SQLite is very flexible: It facilitates you to work on multiple databases on the same session on the same time, Configuration Not Required: SQLite doesn't require configuration. No setup or administration required. SQLite is a cross-platform DBMS: You don't need a large range of different platforms like Windows, Mac OS, Linux, and Unix. It can also be used on a lot of, embedded operating systems like Symbian, and Windows CE. Storing data is easy: SQLite provides an efficient way to store data. Variable length of columns: The length of the columns is variable and is not fixed. It facilitates you to allocate only the space a field needs. For example, if you have a varchar(200) column, and you put a 10 characters’ length value on it, then SQLite will allocate only 20 characters’ space for that value not the whole 200 space. Provide large number of API ‘ALite provides API for a large range of programming languages. For example: .Net languages (Visual Basic, Cif), PHP, Java, Objective C, Python and a lot of other programming language. SQLite Advantages SQLite is a very popular database which has been successfully used with on disk file format for desktop applications. There are a lot of advantages to use SQLite as an application file format: Lightweight ‘SQLite is a very light weighted database so, it is easy to use it as an embedded software with devices like televisions, Mobile phones, cameras, home electronic devices, ete. Jump2earn Publication [www.jump2learn.com]6 Unit- 1 Introduction to SQLite Better Performance © Reading and writing operations are very fast for SQLite database. It is almost 3596 faster than File system. It only loads the dat. which is needed, rather than reading the entire file and hold it in memory. If you edit small parts, it only overwrite the parts of the file which was changed, No Installation Needed © SQlite is very easy to learn. You don’t need to install and configure it. Just download SOlite libraries in your computer and it is ready for creating the database Reliable © Itupdates your content continuously 50, little or no work is lost in a case of power failure or crash. © SQLite is less bugs prone rather than custom written file I/O codes. e SQlite queries are smaller than equivalent procedural codes so, chances of bugs are minimal. Fortable © SQLite is portable across all 32-bit and 64-bit operating systems and big- and little-endian architectures. > Multiple processes can be attached with same application file and can read and write without interfering each other. o It can be used with all programming languages without any compatibility issue, Accessible © SQlite database is accessible through a wide variety of third-party tools. © SQlite database's content is more likely to be recoverable if it has been lost. Data lives longer than code. ee Jump2Learn Publication [www.jump2learn.com] |sme Unit: 1 Introduction to SQLite Zz Reduce Cost and Complexity © It reduces application cost because content can be accessed and updated using concise SQL queries instead of lengthy and error-prone procedural queries. © SQLite can be easily extended in in future releases just by adding new tables and/or columns. It also preserves the backwards compatibility SQLite Disadvantages * SQLite is used to handle low to medium traffic HTTP requests. * Database size is restricted to 2GB in most cases. SQLite Commands SQLite commands are similar to SQL commands. There are three types of SQLite commands: © DDL: Data Definition Language © DML: Data Manipulation Language © DQL: Data Query Language Data Definition Language There are three commands in this group: CREATE: This command is used to create a table, a view of a table or other abject in the database, ALTER: Itis used to modify an existing database object like a table. DROP: The DROP command is used to delete an entire table, a view of a table or other object in the database. Data Manipulation language There are three commands in data manipulation language group: INSERT: This command is used to create a record. UPDATE: It is used to modify the records. Jump2Learn Publication [www.jump2learn,com]8 Unit- 1 Introduction to SQLite DELETE: It is used to delete records. Data Query Language SELECT: This command is used to retrieve certain records from one or more table. SQLite data types Data types in SQLite are different compared to other database management system. In SQLite, you can declare data types normally, but you still can store any value in any data type. SQlite is typed less. There are no data types, you can store any type of datz you like in any column. This is called dynamic types. | In static types, like in other database management systems, if you declared a column with a data type integer, you can only insert values of data type integer However, in dynamic types like in SQLite, the type of the column is determined by the value inserted. And then SQLite stores that value depending on its type. SQLite Storage Classes In SQLite there are different storage methods depending on the type of value, these different storage methods are called storage classes in SQlite. L ‘The following are the storage classes available in SQLite: * NULL - this storage class is used to store any NULL value. * INTEGER — any numeric value is stored as a signed integer value (It can hold both positive and negative integer Values). The INTEGER values in SQluite are - stored in either 1, 2, 3, 4, 6, or 8 bytes of storage depending on the value of the number. * REAL - this storage class is used to store the floating point values, and they are stored in an 8-bytes of storage. «TEXT — stores text strings. It also supports different encoding like UTF-8, UTF, 16 BE, or UTF-26LE. © BLUB — used to store large files, like images or text files. The value is stored as byte array the same as the input value. i Jump2Learn Publication [www jump2learn.com] ERE SECS ETESs cstamae Sage a NO 1 Unit- 1 Introduction to SQLite 9 SQLite Affinity Type ‘SQLite supports the concept of type affinity on columns. Any column can still store any type of data but the preferred storage class for a column is called its affinity. Each table column in SQLite3 database is assigned one of the following type affinities: TEXT This column stores all data using storage classes NULL, TEXT or BLOB. NUMERIC This column may contain values using all five storage classes. INTEGER Behaves the same as a column with NUMERIC affinity, with an exception in a CAST expression. REAL Behaves like a column with NUMERIC affinity except that it forces integer values into floating point representation, NONE Accolumn with affinity NONE does not prefer one storage class over another and no attempt is made to coerce data from one storage class into another. BOLEAN ‘SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (False) and 1 (true). SQLite manifest typing & type affinity Other important concepts related to SQLite data types are manifest typing and type affinity: ‘© Manifest typing means that a data type is a property of a value stored in a column, not the property of the column in which the value is stored. SQLite uses manifest typing to store values of any type in a column. * Type affinity of a column is the recommended type for data stored in that column. Note that the data type is recommended, not required, therefore, a column can store any type of data Jump2Learn Publication (www.jump2learn.com}10 Unit- 1 Ir.iroduction to SQLite SQLite - Transactions A transaction is a unit of work that is performed against a database. ‘Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program. ‘SQLite transaction means it’s a set of T-SAL statements that will execute together as 2 unit like a single T-SQL statement. Ifall these T-SQL statements executed successfully without having any errors then the transaction will be committed and all the changes made by the transaction will be saved to the database permanently. In case, if any error occurred while executing these SQLite statements then the complete transaction will be rollbacked, Generally, the SQLite is in an auto-commit mode that means SQLite automatically starts a transaction for each command, process, and commit the transaction changes automatically to the database, Properties of Transactions Transactions have the following four standard properties, usually referred to by the acronym ACID. + Atomicity ~ Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state. = Consistency - Ensures that the database properly changes states upon a successfully committed transaction. «Isolation - Enables transactions to operate independently of and transparent to each other. , + Durability - Ensures that the result or effect of a committed transaction persists in case of a system failure. Following are the following commands used to control transactions: + BEGIN TRANSACTION - To start a transaction. « COMMIT- To save the changes, alternatively you can use END TRANSACTION command, + ROLLBACK ~ 10 rollback the changes. Jump2Learn Publication [www.jump2learn.com]| Unit- 1 Introduction to SQLite 1 Transactional control commands are only used with DML commands INSERT, UPDATE, and DELETE. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database. BEGIN TRANSACTION Command The BEGIN command is used to start or open a transaction. Once an explicit transaction has been opened, it will remain open until it is committed or rolled back. Following is the syntax of the SQLite BEGIN command. BEGIN; 5 or BEGIN [TRANSACTION]; Here TRANSACTION keyword is optional. SQLite COMMIT Command The COMMIT command is used to close out the current transaction and commit the changes to the database. We can also use the alias END. Following is the syntax of COMMIT command in SQLite. COMMIT [TRANSACTION] > or END [TRANSACTION] Here TRANSACTION keyword is optional Jump2Learn Publication [www.jump2learn.com]12. Unit- 1 Introduction to SQ'ite SQLite ROLLBACK Command By using ROLLBACK command we can cancel the transaction and roll back all the proposed changes. Following is the syntax of the ROLLBACK command, ROLLBACK or ROLLBACK [TRANSACTION] Here also TRANSACTION keyword is optional. ‘The ROLLBACK command will revert all the proposed changes made by the current transaction and then close the transaction Both COMMIT and ROLLBACK will end the current transaction, putting SQlite back into Auto commit mode. Data Filtering SQLite DISTINCT Clause ‘The SQLite DISTINCT clause is used with SELECT statement to eliminate all the duplicate records and fetching only unique records. It is used when you have multiple duplicate records in the table. syntax: SELECT DISTINCT columni, column2,....columnN FROM table_name WHERE [condition] Jump2Learn Publication [www jump2learn.com]| | Unit- 1 Introduction to SQLite 3 Example: We have a table named "STUDENT", having the following data First Select NAME from "STUDENT" without using DISTINCT keyword, It will show the duplicate records: Output: Now, select NAME from "STUDENT" using DISTINCT keyword, SELECT DISTINCT NAME FROM STUDENT; Output: Ee ek el a Saas Oe Jump2Learn Publication [www.jump2learn.com]4 nit- 1 Introduction to SQLite SQLite WHERE Clause The SQlite WHERE clause is generally used with SELECT, UPDATE and DELETE statement to specify a condition while you fetch the data from one table or multiple tables if the condition is satisfied or true, it returns specific value from the table. You would lise WHERE clause to filter the records and fetching only necessary records WHERE clause is also used to filter the records and fetch only specific data. syntax: SELECT columni, column?, column FROM table_name WHERE [condition] Example: Teche example, we are using WHERE clause with several comparison and logical operators. like >, <, =, LIKE, NOT, ete. We have a table student having the following data: el Command Prompt ~sqlite3 s1P.db ro Sn pier Examplel: Select students WHERE age is greater than or equal to 25 and fees is greater than or equal to 10000.00 SELECT * FROM STUDENT WHERE AGE >= 25 AND FEES >= 1000.00; Jump2Learn Publication [www jump2tearn.com]ERR: oe RM i i Unit- 1 Introduction to SQI Output: [Hi Command Prompt - sqlite} sTP.db oa SQLite BETWEEN Clause ‘The SQlite BETWEEN is used to select those values that are within a range of two values. For example, "X BETWEEN Y AND 2” will return true (1) if the value X is, between the two values ¥ and Z. Otherwise, it will return false (0). "X BETWEEN Y AND. 2" is equivalent to "X >= Y AND X <= 2", X must be greater than or equal to Y and X is less than or equal to Z. Example: In the following example query, we will write a query to get students with Id value between 5 and 8: SELECT * FROM Students WHERE Studentld BETWEEN 5 AND 8; This will give only the students with ids 5, 6, 7, and 8: sqlite SELECT « Beream SU mg ate} ‘ : : Perea seeker ag O eis) oa tt ab es SAUCE he CTs cen Gem Leela corer oC pee 1998-16-12 ll Nicaea tires) Jump2Learn Publication [www_jump2learn.com]SQLite IN Clause The SQLite IN clause takes one operand and a lst of operands. It will return true ifthe first operand value equal to one of the operands’ value from the list The IN operator return true (1) ifthe lst of operands contains the first operand value within its values. Otherwise, it will return false (0) Like this: “col IN(x, y, 2)". Tis is equivalent to " (cot=x) or (coley) oF (col Example: ‘The following query will select students with ids 2, 4, 6, 8 only SELECT * FROM Students WHERE Studentid IN(2, 4, 6 8); | a a Students eK lea The previous query will give the exact result as the following query because they are equivalent SELECT * FROM Students WHERE (Studentid = 2) OR (Studentid = 4) OR (Studentld = 6) OR (Studentid = 8); SQLite NOT IN Clause Thp Slite NOT IN clause operand isthe opposite of the IN operator But with the same syntax, it takes one operand and a lst of operands. It will return true if the first Sperand value not equal to one of the operands! value from the list.ie,, it will return tue (0) thelist of operands doesn’t contain the first operand. Fike this: "col NOT IN(s y, 2)". This is equivalent to "(col<>x) AND (coly) AND {col-~2)" ‘Jump2Learn Publication [www.jump2learn.com}i ence oo soe Unit- 1 Introduction to SQLite 7 Example: The following query will select students with ids not equal to one of these Ids 2, 4, 6, 8 SELECT * FROM students WHERE Studentid NOT IN(2, 4, 6, 8); > FROM Stud Utila eterna etn Li bkelre Jack Ren Nanc Sian Certo ania SQLite LIKE Clause SQLite LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. There are two wildcards used in conjunction with the LIKE operator ~ + The percent sign (%) + The underscore (_) The percent sign represents zero, one, or multiple numbers or characters. The underscore represents a single number or character. These symbols can be used in combinations, Syntax: Following is the basic syntax of % and _ SELECT FROM table_name WHERE column LIKE 'XXXX96" Jump2Learn Publication [www.jump2learn.com)18. Unit- 1 Introdut or SELECT FROM table_name WHERE column LIKE '_XXXX_! Example: sqlite> SELECT * FROM COMPANY WHERE ADDRESS LIKE '%- Output: ID NAME AGE ADDRESS SALARY 3 aj 66 Rander-Road 5000.0 8 deep 12 ram-nagar 7000.0 SQLite - UNION Clause Site UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows. To use UNION, each SELECT must have the same number of columns selected, the same number of column expressions, the same data type, and have them in the same order, but they do not have to be of the same length. syntax Following is the basic syntax of UNION. SELECT columni [, column? ] FROM table! [, table2 } [WHERE condition} UNION SELECT columnt [, column? } FROM table! (, table? ] [WHERE condition] Example: ‘SELECT ID FROM STUDENT UNION , SELECT ID FROM DEPARTMENT; Jump2Learn Publication [www jump2learn.com]Unit- 1 Introduction to SQLite 19 The following picture illustrates the UNION operation of t1 and t2 tables: T1 UNION T2 SQLite Intersect SQLite INTERSECT operator compares the result sets of two queries and returns distinct rows that are output by both queries. Syntax: SELECT select_list * ‘ FROM tablet INTERSECT SELECT select_list2 FROM table2 7 Jump2Learn Publication [www.jump2learn.com]20 Unit- 1 Introduction to SQLite ‘The basic rules for combining the result sets of two queries are as follows. + First, the number and the order of the columns in all queries must be the same. + Second, the data types must be comparable. ‘The following picture illustrates the INTERSECT operation OO-W T1 INTERSECT T2 SQLite Except SQLite EXCEPT operator compares the result sets of two queries and returns distinct rows from the left query that are not output by the right query. syntax: SELECT select_list1 FROM tablel EXCEPT SELECT select_list2 FROM table2 ‘This query must conform to the following rules: + First, the number of columns in the select lists of both queries must be the same. + Second, the order of the columns and their types must be comparable. Jump2Learn Publication [www.jump2learn.com]Unit- 1 Introduction to SQLite 21 The following picture illustrates the EXCEPT operation: w TL T2 T1 EXCEPT T2 SQLite LIMIT Clause The SQlite LIMIT clause is used to limit the data amount fetched by SELECT command froma table. Syntax: SELECT column1, column2, column FROM table_name LIMIT [no of rows] ‘The LIMIT clause can also be used along with OFFSET clause. SELECT column1, column2, column FROM table_name UMIT {no of rows] OFFSET [row num] Example1: Fetch the records from the "STUDENT" table by using LIMIT according to your need of number of rows. SELECT * FROM STUDENT LIMITS; Jump2Learn Publication [www.jump2learn.com]22 Unit- 1 Introduction to SQLite TH conmand Pomel -9ta a e be 2 ie) ST Het SQLite GROUP BY Clause ‘The SQLite GROUP BY clause is used with SELECT statement to collaborate the same identical elements into groups. The GROUP BY clause is used with WHERE clause in SELECT statement and precedes the ORDER BY clause. syntax: SELECT column-list FROM table_name WHERE [ conditions } GROUP BY column1, colurmn2....columnN ORDER BY columni, column2....columnN Example: Use the GROUP BY query to know the total amount of FEES of each student: SELECT NAME, SUM(FEES) FROM STUDENT GROUP BY NAME; [Command Prompt ages TPdb ra ae Ray cy $000.0 ce} ) Jump2Learn Publication [www jump2learn.com]Unit- 1 Introduction to SQlite 23 SQlite HAVING Clause The SQLite HAVING clause is used to specify conditions that filter which group results appear in the final results. The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by the GROUP BY clause. ‘The position of HAVING clause in a SELECT query: syntax: SELECT column1, column2 FROM tablel, table2 WHERE [ conditions ] . GROUP BY column1, column HAVING [ conditions } ORDER BY column1, column2 Example: sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) > 2 output: ID NAME AGE ADDRESS SALARY 45 rajan 56 Surat 7500 SQLite CASE os ‘The SQLite CASE expression evaluates a list of conditions and returns an expression based on the result of the evaluation. : The CASE expression is similar to the If-THEN-ELSE statement in other programming languages. You can use the CASE expression in any clause or statement that accepts a valid expression. For example, you can use the CASE expression in clauses such as WHERE, ORDER BY, HAVING, SELECT and statements such as SELECT, UPDATE, and DELETE. Jump2Learn Publication [www.jump2learn.com]24 Unit: 1 Introduction to SQLite syntax: CASE case_expression WHEN when_expression_1 THEN result_1 WHEN when_expression_2 THEN result_2 [ELSE result_else } END ‘The simple CASE expression compares the case_expression to the expression appears in the first WHEN clause, when_expression_1, for equality. Ifthe case_expression equals when_expression_1, the simple CASE returns the expression in the corresponding THEN clause, which is the result_1 Otherwise, the simple CASE expression compares the case_expression with the i expression in the next WHEN clause. Incase no case_expression matches the when_expression, the CASE expression returns the result_else in the ELSE clause. If you omit the ELSE clause, the CASE expression returns NULL. ‘The simple,CASE expression uses short-circuit evaluation, In other words, it returns the result and stop evaluating other conditions as soon asit finds a match, Example: SELECT customeri¢, , firstname, lastname, CASE country WHEN ‘USA’ THEN 'Domestic’ ELSE ‘Foreign’ END CustomerGroup FROM customdrs Jump2Learn Publication [www.jump2learn.com]Ee 2 ee REECE EET) A SERRE cing pee ee uni 1 Introduction to SQLite 20 SQLite joins: In SQLite, JOIN clause is used to combine records from two or more tables in a database. It unites fields from two tables by using the common values of the both table. ‘There are mainly three types of Joins in SQLite: © SQLite INNER JOIN © SQLite OUTER JOIN © SQLite CROSS JOIN ‘SQLite Inner Join The SQLite Inner join is the most common type of join. It is used to combine all rows from multiple tables where the join condition is satisfied. ‘The SQlite Inner join is the default type of join Syntax: SELECT ... FROM table1 [INNER] JOIN table? ON conditional_expression oR SELECT ... FROM table1 NATURAL JOIN table2... tablet table2 Example: SELECT EMP_ID, NAME, DEPT FROM STUDENT INNER JOIN DEPARTMENT ' ON STUDENT.ID = DEPARTMENT. EMP_ID; ° SQLite Outer Join In SQL standard, there are three types of outer joins: © Left outer join © Right outer join © Full outer join. But, SQLite suppérts only Left Outer Join. Jump2Learn Publication [wwwjump2learn.com]26 SQlite Left Outer Join 1 Introduction to SQlite The SQLite left outer join is used to fetch all rows from the left hand table specified in the ON condition and only those rows from the right table where the join condition Is satisfied syntax: SELECT ... FROM table1 LEFT OUTER JOIN table2 ON conditional_expression SELECT ... FROM table1 LEFT OUTER JOIN table2 USING ( colurmnt , Example: SELECT EMP_ID, NAME, DEPT FROM STUDENT LEFT OUTER JOIN DEPART MENT The CROSS JOIN (ON STUDENT.ID = DEPARTMENT.EMP_ID; or TEs o. CROSS,OIN matches every row of the first table with every row of the second table. f ul Because CROSS JOINs have the potential put tablas have x and y row, respectively, the resulting table will have x*y row. to generate extremely large tables, care must be taken to only use them when appropriate, t jump2Learn Publication [www.jump2learn.com]Unit- 1 Introduction to Sl 27 Syntax : SELECT ... FROM table CROSS JOIN table2 .. Cross Join Example: sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY CROSS JOIN DEPARTMENT; SQLite Trigger SQLite Trigger is an event-driven action or database callback function which is invoked automatically when an INSERT, UPDATE, and DELETE statement is performed on a specified table. The main tasks of triggers are like enforcing business rules, validating input data, and keeping an audit trail a Usage of Triggers: 0 Triggers are-used for enforcing business rules. © Validating input data. © Generating a unique value for a newly-inserted row in a different file. © Write to other files for audit trail purposes. 0 Query from other files for cross-referencing purposes. © Used to access system functions. © Replicate data to different files to achieve data consistency, Jump2Learn Publication [www.jump2learn.com]28 Unit- 1 Introd. Advantages of using triggers: Triggers make the application development faster. Because the database stores triggers, you do not have to code the trigger actions into each database application. Define a trigger once and you can reuse it for many applications that use the database. Maintenance is easy. If the business policy changes, you have to change only the corresponding trigger program instead of each application program. SQLite CREATE TRIGGER : To create a new trigger in SQLite, you use the CREATE TRIGGER statement as follows: syntax: CREATE TRIGGER [IF NOT EXISTS] trigger_name [BEFORE] AFTER] INSTEAD OF} [INSERT| UPDATE | DELETE] ON table_name [WHEN condition] BEGIN statements; END; In this syntax: First, specify the name of the trigger after the CREATE TRIGGER keywords. Next, determine when the trigger is fired such as BEFORE, AFTER, or INSTEAD OF. You can create BEFORE and AFTER triggers on a table. However, you can only create an INSTEAD OF trigger en a view. Then, specify the event that causes the UPDATE, or DELETE. After that, indicate the table to which the trigger belongs. Finally, place the trigger logic in the BEGIN END block, which can be any valid yer to be invoked such as INSERT, SQL statements, If you combine the time when the trigger is fired and the event that causes the trigger tobe fi red, you have a total of 9 possibilities: BEFORE INSERT AFTER INSERT BEFORE UPDATE AFTER UPDATE eee Jump2Learn Publication [www.jump2learn.com]Unit-1 Introduction to SQLite 29 BEFORE DELETE AFTER DELETE INSTEAD OF INSERT INSTEAD OF DELETE INSTEAD OF UPDATE Suppose you use a UPDATE statement to update 10 rows in a table, the trigger that associated with the table is fired 10 times. This trigger is called FOR EACH ROW trigger. If the trigger associated with the table is fired one time, we call this trigger a FOR EACH STATEMENT trigger. You can access the data of the row being inserted, deleted, or updated using the OLD and NEW references in the form: OLD.column_name and NEW.column_name. The following table illustrates the rules INSERT NEW is available UPDATE Both NEW and OLD are available DELETE OLD is available Example: SQLite BEFORE INSERT trigger. Suppose you want to validate the email address before inserting a new lead into the leads table. In this case, you can use a BEFORE INSERT trigger. First, create a BEFORE INSERT trigger as follows: CREATE TRIGGER validate_email_before_insert_leads BEFORE INSERT ON leads BEGIN SELECT + CASE WHEN NEW.email NOT LIKE '%_@_%._96' THEN RAISE (ABORT, ‘Invalid email address') END; END; Jump2Learn Publication [www.jump2learn.com]‘i 30 Unit- 1 Introduction to SQLite SQLite DROP TRIGGER statement To drop an existing trigger, you use the DROP TRIGGER statement as follows: syntax: DROP TRIGGER [IF EXISTS] trigger_name; In this syntax: «First, specify the name of the trigger that you want to drop after the OROP TRIGGER keywords. «Second, use the IF EXISTS option to delete the trigger only if it exists. Note that if you drop a table, SQLite will automatically drop ell triggers associated with the table. s i} Exercise | Short Question i 1. What is SQLite? Hl 2. What datatype does SQLite supports? ia 3. What is the use of LIMIT clause with SELECT query? 4, Why is ORDER BY clause used with SELECT statement? 5. What is the use of SQLite GROUP BY clause? 6. What is the use of DISTINCT clause in SQLite? 7. Explain Commit and rollback. Long Question ‘What are the advantages of using SQlite? Explain SQLite commands. ‘What is the difference between SQL and SQLite? , Explain the different type of join in SQLite. What is UNION operator? How does it work? Explain Triggers and types of trigger with example oyaeNe Jump2Learn Publication [www.jump2learn.com]Unit - 2 Database backup and CSV handling Jump2Learn Publication [www.jump2learn.com]32, Unit-2 Database backup and CSV handling SQLite dump The SQLite dump command to backup and restore a database. _dump command that gives you the ability to dump the entire database or tables into a text file Dump the entire database into a file To dump a database into a file, you use the dump command. The .dump command converts the entire structure and data of an SQLite database into a single text file. By default, the dump command outputs the SQL statements on screen. To issu the output to a file, you use the .output FILENAME command. The following command opens a new SQLite database connection to the student.db file. C:\sqlite>sqlite3 c:/sqlite/ student.db SQLite version 3.33.0 2021-06-05 10:57:30 Enter ".help" for usage hints. sqlite> ‘The following commands specify the output of the dump file to student.sql and dump the student database into the student.sal file. sqlite> .output c:/sqlite /student.sql sqlite> dump sqlite> .exit Dump a specific table using the SQLite dump command If you want to dump a specific table, you need to specify the table name followed the .dump command. For example, the following command saves the albums table to the albums.sq| file. sqlite> .output c:/sqlite/albums.sql sqlite> dump albums sqlite> .quit Jump2Learn Publication [www jump2learn.com]Unit-2 Database backup and CSV handling 33 ‘The following picture shows the content of the albums.sq] file PRAGMA foreign _keys-oFF; SIBEGIN TRANSACTION; CREATE TABLE "alban" a T” (atbuntd) SWVTEGER PRIMARY KEY AUTOTNCREMENT NOT NOLL, [Tivie] NVARCHAR(260) NOT NULL, [rcistid) INTEGER NOT NULL, FOREIGN KEY ({ArcistId]) REFERENCES ON DELETE NO ACTION ON UPDATE NO ACTION (Breiseidy) ve INSERT INTO "albums" VALUES (1, 'F INSERT INTO "atbuns” VALUES(2, "3211. INSERT INTO "albuns” INSERT INTO "aibuns” INSERT INTO "albums" INSERT INTO “albune" INSERT INTO “albure’ TNSERT THTO. "Albuns" mm jock We Salute You',i); Dump tables structure If you want to dump the structures of tables in a database, you use the .schema command. The following commands set the output file to student.sq] file and save the structures of tables into the student.sq| file. sqlite> .output c:/salite/ student. sql sqlite> schema sqlite> quit Dump data of one or more tables into a file To dump the data of a table into a text file, you use these steps: First, set the mode to insert using the mode command as follow sqlite> mode insert From now on, every SELECT statement will issue the result as the INSERT statements instead of pure text data Second, set the output to a text file ‘instead of the default standard output. The following command sets the output file to the record.sa| file. sqlite> output record.sql Jump2Learn Publication [www jump2learn.com]34 Unit-2 Database backup and CSV handling ‘Third, issue the SELECT statements to query data from a table that you want to dump. The following command returns data from the student table. sqlite> select * from student; Check the content of the record.sq] file. To dump data from other tables, you need to issue the SELECT statements to query data from those tables. CSV files handling Import a CSV file into a table We want to import data from CSV file into a table that does not exist in the SQLite database, «* First, the sqlite3 tool creates the table. The sqlite3 tool uses the first row of the CSV file as the names of the columns of the table. Second, the sqlite3 tool import data from the second row of the CSV file into the table. We will import a CSV file named city.csv with two columns: name and population. To import the c:\sqlite\city.csv file into the cities table: First, set the mode to CSV to instruct the command-tine shell program to interpret the input file as a CSV file, To do this, you use the mode command as follows: > mode csv Second, use the command .import FILE TABLE to import the data from the city.csv file into the cities table. sqlite>.import c:/sqlite/city.csv cities To verify the import, you use the command schema to display the structure of the cities table. sqlite> schema cities CREATE TABLE cities ( “name” TEXT, population” TEXT js The table is already available in the database and you just need to import the data, Jump2Learn Publication [www.jump2learn.com]yf Unit-2 Database backup and CSV handling 35 First, use t! e following CREATE TABLE statement to create the table cities. CREATE TABLE cities ( name TEXT NOT NULL, population INTEGER NOT NULL i If the table already exists, the sqlite3 tool uses all the rows, including the first row, in the CSV file as the actual data to import. Therefore, you should delete the first row of the CSV file, The following commands import the city_without_header.csv file into the cities table. sqlite> mode csv sqlite> import c:/sqlite/city_no_header.csv cities Export a CSV file from table By using the sqlite3 tool, you can use the SQL statements and dot-commands to interact with the SQLite database. To export data from the SQLite database to a CSV file, you use these steps: 1, Turn on the header of the result set using the header on command, 2. Set the output mode to CSV to instruct the sqlite3 tool to issue the result in the CSV mode. 3. Send the output to a CSV file. 4, Issue the query to select data from the table to which you want to export. ‘The following comands select data from the customers table and export it to the data.csv file. >sqlite3 c:/sqlite/chinook.db sqlite> headers on sqlite> mode csv sqlite> output data.csv - sqlite> SELECT customerid, 0 > firstname, .> lastname, > company Jump2Learn Publication [www.jump2learn.com], a36. Unit-2 Database backup and CSV handling > FROM customers; sqlite> quit, If you check the data.csv file, you will see the following output. custonerTd, FiretName, LastName, Company cetrets", "Gongalves™, "Embraer - Empresa Brasileira de Aeronéucica $-A." 2, Leonie, "Kohler", 3, "Frangois", Tremblay, 4, "Bjorn", Hansen, S.nFrantiger", "Wichterlova", "JetBrains 3.5.0." 6,Helena, "HOLY", qiastrid, Gruber, @,Daan, Peeters, 9, Kara, Nielsen, 10,Eduardo,Martins, "Woodstock Discos” ti lalexandre, Rocha. "Banco do Brasil 5.2." Besides using the dot-commands, you can use the options of the sqlite3 tool to export data from the SQLite database to a CSV file. For example, the following command exports the data from the tracks table to a csv file named tracks.csv >sqlite3 -header -csv :/sqlite/chinook.db “select * from tracks)" > tracks.csv qoackI4;, Hane, Albund, MediaTypeTd, Genteld, Composer, MilLisesends, Bytes, uniePs tee Trae eceoe about To Rock (We Salute You)*,1,1,2,"Angus Young, Maleotm Young, Dt aimpaila to the Wall",2,2, 2, , 342562, 5520424, 0.99 Sinpast As a Shark",3,2/1,"F. Baltes, S. Kaufman, J. Dirkscnesder § fy Hoftman",? serReeE rede ana wilars3/2/,"F- Balces, R.A. Smith-Diesel, S$. Kaufman, 2. Doses SOTREIEEESS of che Davn*,3,2,1,"Deafty & R.A, Smith-Diesel", 375428, 6290520, 0.02 eUipae The Finger On You",1,1,1,"Angus Young, Malcolm Young, Brian Johnson", 20566| Satetts Get Te Opt, 1,2,2,"Angus Young, Malcolm Young, Brian Johnaen", 233926, 7636 areinjece The Venom", 1,2, 1,"Angus Young, Heicolm Young, Brsan Jonnaon”, 210834, 685 o,snowballed,1,2,2,"angus Young, Malcolm Young, Brian Johnaon 203102, 6599424, 0.9 10, "evil Walks™,1,1,1,"Angus Young, Malcolm Young, Brian Johnson", 263497, 8611245,' se rep ieisz "angus Young, Malcolm Young, Brian Johnson”, 199836, 6566544, 0-08 a eroctiing ine Aules™, 1,1,4, "Angus Young, Malcolm Young, Brian Johnson" 265900, Solmuigne Of The ong Keives",1,2,2, "Angus Young, Matcolm Young, Desae Jahngon",2 ia, spelibound, 1,1,1, "Angus Young, Maicolm Young, Brian ‘Johnson, 270863, 8817036, 0 15, "Go Down", 4, !,1,AC/DC, 331180, 10847611,0.99 if you have a file named query.sql that contains the script to query data, you can execute the statements in the file and export data to a CSV file. >sqlite3 -header -csv c:/salite/chinook.db < query.sql > data.csv Jump2Learn Publication [wwwjump2learn.com]ng, Br: man", 2 azkect! 0.99) 120866: 6, 7636 34, 688: 24,0.9 11245, 0.99 63288, son”, 2! 938, 0. Unit-2 Database backup and CSV hendling 37 Exercise Short Question 1. Define dump command. 2. What is CSV file. Long Question 1, How to Dump the entire database into a file? 2, How Dump a specific table using the SQLite dump command? 3. Explain how to Import a CSV file into a table. 4, Write Steps to Exports data from the SQLite database to a CSV file Jump2Learn Publication [www.jump2learn.com}38 Unit-2 Database backup and CSV handling Jump2Learn Publication [www jump2learn.com]— __Unit-3 Python Interaction with SQLite 39 Unit - 3 Python Interaction with SQLite | Jump2Learn Publication [www.jump2learn.com]hon Interaction with S¢ 40 Module Python module can be defined as a python program file which contains 2 python code including python functions, class, or variables. In other words, we can say that our python code file saved with the extension (py) is treated as the module, We may have a runnable code inside the python module. Modules in Python provides us the flexibility to organize the code in a logical way. To use the functionality of one module into another, we must have to import the specific module. Create a Module To create a module just save the code you want in a file with the file extension -Py: Example Save this code in a file named mymodule.py def display(name): print("my name, "+name) Here, we need to include this module into our main module to call the method display () defined in the module named file. _ Loading the module Python provides two types of statements as defined below. 1, The import statement 2. The from-import statement The import statement The import statement is used to import all the functionality of one module into another, Here, we must notice that we can use the functionality of any python source file by importing that file as the module into another python source file. We can import multiple modules with a single import statement, but a module is loaded once regardless of the number of times, it has been imported into our file. syntax: import module1,module2, modules ...... module n i Jump2Learn Publication [www jump2learn.com]Unit-3 Python Interaction with SQLite a1 Hence, if we need to call the function display () defined in the f"e mymodule.py, we have to import that file as a module into our module as shown in the example below. Example: import file; name = input("Enter the name: ") file.display(name) Output: Enter the name: mayank myname , mayank The from-import statement Python provides the flexibility to import only the specific attributes of a module. This can be done by using from - import statement. ‘Syntax > from< module-name> import
,
..,
Example: from file import display; name = input("Enter the name: ") file.display(name) Output: Enter the name: mayank my name, mayank We can also import all the attributes from a moddle by using * Consider the following syntax, from
import * Jump2Learn Publication [www.jump2learn.com]PYTHONPATH PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. For most installations, you should not set these variables since they are not needed for Python to run. Python knows where to find its standard library. The only reason to set PYTHONPATH is to maintain directories of custom Python libraries that you do not want to install in the global default location (i.e., the site- packages directory). Setting PYTHONPATH on a windows machine follow the below steps: Step 1: Open your This PC (or My Computer) and write click and click on properties. Step 2: After window pop up click on to Advance System Settings Dine ~~ = 8 1s contr amass er eects ng * | i Windows10 sy ‘4 py yt ben pe | Pontes tahoe hipeotely \ ne NOT Sonor 2 mane RS Gongrenin | Step 3: Now click on the environment variable button in the new popped up window as shown below: aT Jump2Learn Publication [www.jump2learn.com]Unit-3 Python Interaction with SQLite 43 Sytem ropes x (ampere Hanae Maced | Sytem Ftecion | Renae ‘eum egg on 32nd make ot thee changes Peomance Vin ees pace eal. mano wage and a ena er Petes Deion striae tar wa Same a Rooney Stan at, sane an ebuggy lemtan Step 4: Now in the new Environment Variable dialog box click on New as shown, below: Eine Vibes x (C\Usen\Admncttr Appa Local Miso Windows | pymioneamt (Ure Hamar | re tee drintn dppDatlocah Teng | np vee RdmaitatonappDatloca ong Pet ——e oe aoe cnet cd aceon eae feestonenemerac eee a Jump2Learn Publication [www.jump2learn.com]—————— 44. Unit-3 Python Interaccion with SQLite Step 5: Now in the variable dialog box add the name ¢ the variable as PYTHONPATH and in value add the location to the module directory that you want python to check every time as shown below: it User Variable Vojablename __[PYTHONPATH| uojeone, [Aenean Your PYTHONPATH is set Concepts of Namespace and Scope In python we deal with variables, functions, libraries and modules ete. There is @ chance the name of the variable you are going to use already existing as name of another variable of as the name of another function oF another method. In such cenario, we need to learn about how all these names ate managed by 2 python program. This isthe concept of namespace its Name {which means name, a unique identifier) + space (which talks something related to scope). Here, a name might be of any python method or variable and space depends upon the location from where is trying to access a variable or a method. Following are the three categories of namespace «Local Namespace: All the names of the functions and variables declared by a program are held in this namespace. This namespace exists as long as the program runs. < /p> |. Global Namespace: This namespace holds all the names of functions and ether variables that are included in the modules Pein used in the python program. it encompasses all the names that are Part of the Local namespace. || Built-in Namespace: This is the highest level of namespace which is available with default names available as part of the python interpreter that is loaded as the programing environment. It encompasses Global Namespace which in turn ‘encompasses the local namespace. Jumpatearn Publication (wivw jump2tearn.comlType of Namespaces Scope of Namespace ‘The namespace has a lifetime when it is available. That is also called the scope. Also the scope will depend on the coding region where the variable or object is located. You can see in the below program how the variables declared in an inner loop are available to the outer loop but not vice-versa. Also please note how the name of the outer function also becomes part of a global variable. Example prog_var='Hello’ 7 defouter_func(): outer_var ='x' definner_func(): inner_var ='y' print(dir(),* Local Variable in Inner function’) inner_fune() print(dir(), Local variables in outer function’) outer_fune() print(dir(), “Global variables ') “Output Cinner_var'] Local Variable in Inner function inner_func’, ‘outer_var'] Local variables in outer function Jump2Learn Publication [www.jump2learn.com]46 Uni \_annotations_', "__builtins_', "_cached_’ = \_loader_ \__package_',"__spec_', ‘outer_func’,‘prog_var'] Global variables Packages in Python ‘name 1A package is @ hierarchical file directory structure that defines 2 single Python application environment that consists of modules and subpackages and sub subpackages, and so on Consider a file Display.py available in pack1 directory. This file has following line of source code ~ def displ) print “student doing bea" similar way, we have another two files having different functions with the same name as above ~ + pack1/a1.py file having function a1() « pack1/b1.py file having function b1() Now, create one more file init__.py in pack1 directory ~ + pack1/_init_.py To make all of your functions available when you've imported pack , you need to put explicit import statements in _ init__py as follows ~ fi Now import your pack1 Package. import pack1 pack1.disp() pack1.al() pack1.b1() Output: student doing bea this is from a1 this is from b1 inthe above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define different Python dlasses in those files and then you can create your packages out of those classes. Jump2Learn Publication [www.jump2learn.com]Unit-3 Python Interaction h SQLite: a7 Importing sqlite3 module SQLite3 can be integrated with Python using sqlite3 moduie, which was written by Gerhard Haring. It provides an SQL interface compliant with the DB-API 2.0. You do not need to install this module separately because it is shipped by default along with Python version 2.5.x onwards. To use sqlite3 module, you must first create a connection object that represents the database and then optionally you can create a cursor object, which will help you in executing all the SQL statements. Importing sqlite3 : import sqlite3 connect() {This routine opens a connection to the SQLite database file. You can use “memor to open a database connection to a database that resides in RAM instead of on disk. If database is opened successfully, it returns a connection object. When a database is accessed by multiple connections, and one of the processes modifies the database, the SQlite database is locked until that transaction is committed. The timeout parameter specifies how long the connection should wait for the lock to go away until raising an exception. The default for the timeout parameter is 5.0 (five seconds). » If the given database name does not exist then this call will create the database. You can specify filename with the required path as well if you want to create a database anywhere else except in the current directory Syntax: sqlite3.connect(database [,timeout ,other optional arguments}) Example: import sqlite3 conn = sqlite3.connect(student.db') print "Opened database successfully"; Now connection is created with the student database. Execute() This routine executes an SQL statement. The SAL statement may be parameterized (i e. placeholders instead of SQL literals). The sqlite3 module supports two kinds of placeholders: question marks and named placeholders (named style). Jump2Learn Publication [www.jump2learn.com] 4Unit-3 Python Interaction with SQLite ag syntax: cursor.execute(sql [, optional parameters}) For example ~ cursor.execute("insert into student values (?, 2)", (who, age)) fetchone() fetchone(} method returns a single record or None F no more rows are available. To fetch a single row from a result set we can use cursor.fetchone(). This method returns a single tuple. Tt can return a none if no rows are available in the resultset. cursor fetchonel) increments the cursor position by one and return the next row. * syntax: | cursor-fetchone() Example: import sqlite3 try: connection = sqlite3.connect(student.db') cursor = connection.cursor{) print("Connected to database") query = "SELECT * from student” cursor.execute(query) print("Fetching single row") 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") Jump2Learn Publication [www jump2learn.com]Unit-3 Python Interaction with SQLite 49 Output: Connected to database Fetching single row (1, ‘amit’, 'BCA’,88) Fetching next row (2, ‘rani, Mca',98) The Sqlite connection is closed fetchall() fetchall() method fetches all (remaining) rows of a query result, returning a list. An ‘empty list is returned when no rows are available. Get resultSet (all rows) from the cursor object using a cursor.fetchall() Example: import sqlite3 try: connection = sqlite3.connect{'student.db') cursor connection.cursor() print("Connected to SQLite") query = "SELECT * from student" cursor.execute(query) records = cursor fetchall() print("Total rows are: ", len(records)) print("Printing each row") for row in records: print("Id:", row{0}) print("Name: ", row(1]) print("“course: ", row{2]) print("marks: ", row(3}) print("\n") cursor.close() except sqlite3.Error as error: print("Failed to read data from table", error) Jump2Learn Publication [www jump2learn.com}50. Unit-3 Python Interac finally: if connection: connection.close() print("The Sqlite connection is closed") Output: Connected to database Total rows are: 3 Printing each row Id: 1 : Name: raj course: BCA marks: 88 ld: 2 Name: rani course: MCA marks: 99 Id: 3 Name: deep course: BCA : marks: 50 The Sqlite connection is closed Create a table using python Create a table "STUDENT" within the database “demo_db". Create a python file “createtable.py”, having the following code: import sqlite3 conn = sqlite3.connect('demo_db') print “Opened database successfully"; conn.execute("CREATE TABLE STUDENT Jump2Learn Publication [www jump2learn.com]Unit-3 Python Lateraction with SQLite 51 (ID INT PRIMARY KEY NOTNULL, NAME TEXT NOT NULL, AGE INT NOTNULL, ADDRESS CHAR(SO) x") print ("Table created successfully") conn.close() A table "STUDENT "is created in the "demo_db" database. Insert Records Insert some records in" STUDENT " table. Create a python file "insert.py", having the following code: import sqlite3 conn = sqlite3.connect(‘javatpoint.db') print ("Opened database successfully") conn.execute("INSERT INTO STUDENT (ID,NAME,AGE,ADDRESS) VALUES (1, ‘aditya’, 27, ‘surat’ )") conn.commit() print ("Recdrds inserted successfully") conn.close() output: Opened database successfully Records inserted successfully , Jump2Learn Publication [www jump2learn.com]ith SQLite 52. Unit-3 Python Interaction Select Records To fetch and display your records from the table "STUDENT" by using SELECT statement Create a python file "select. py", having the following code: import sqlite3 conn = sqlite3.connect{ javatpoint.db') data = conn.execute("select * from Employees") for row in data: print ("ID=", row[0] ) print ("NAME =", row[2] ) print ("AGE =", row(2} ) print ("ADDRESS = ", row(3],"\n") conn.closel); Output: 1D=1 NAME =aditya AGE=27 ADDRESS =surat Io NAME =raj AGE=32 ‘ADDRESS =vapi Delete Records Delete some records in " STUDENT " table. Create a python file “delete.py", having the following code: import salite3 conn = sqlite3.connect('javatpoint.db’) print ("Opened database successfully") id = int(input(“Enter id to delete:") Jump2Learn Publication [www.jump2learn.com]Unit-3 Python Interaction with S.tLite 53 conn.execute("DELETE “ROM STUDENT WHERE ID = ",id) conn.commit() print ("Total number of rows deleted :", conn.total_changes) conn.close() Output: Opened database successfully Enter id to delete:1 Total number of rows deleted :1 total_changes Returns the total number of database rows that have been modified, inserted, or deleted since the database connection was opened commit() commit() method commits the current transaction. If you don’t call this method, anything you did since the last call to commit() is not visible from other database connections. If you wonder why you don’t see the data you've written to the database, please check you didn’t forget to call this method, Example: import sqlite con = sqlite3.connect('demo_db') cur = con.cursor() con.execute("""CREATE TABLE student (id integer, value text)""") con.execute("INSERT INTO student VALUES (1, ‘mehul')") con.commit() result = con.execute("SELECT * from student") for row in result: print (row) Output: (1, 'mehul’) Here we create one table in demo_db database and insert one record using execute() method and then commit() method call to commits the current transaction and then. data was display from database using select query using execute () method. I Jump2Learn Publication [www.jump2learn.com]Short Question 1. Define Module: 2. Explain PYTHONPATH. 3. Define Packages. 4, Difference between fetchone() and fetchalll) methods. 5. Explain commit () method Long Question How to load module in code? 1 2. Explain Concepts of Namespace and Scope. 3. Explain Packages in Python. 4. Explain connect () and execute() methods of sqlite3 module. 5, Write a code to Insert, update, delete using execute () method in below table student_tbi{id, name, dob, class, gender, city) Jump2Learn Publication [www.jump2learn.com]Unit-4 Python Interaction with text and CSV 55 Unit - 4 Python interaction with SQLite i Jump2Learn Publication [www jump2learn.com]
You might also like
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6125)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (627)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brené Brown
4/5 (1148)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (932)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4/5 (8214)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (631)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1253)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4/5 (8365)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (860)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (877)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (954)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4/5 (2922)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (484)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (277)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Toibin
3.5/5 (2061)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (4972)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (444)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4281)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (447)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1068)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1987)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (278)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (1993)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2619)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (1936)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (125)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (692)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (1912)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4074)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (75)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (143)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (901)
Arihant JNV Class 9 Jawahar Navodaya Vidyalaya 2022 Edition
PDF
0% (5)
Arihant JNV Class 9 Jawahar Navodaya Vidyalaya 2022 Edition
417 pages
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2530)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M L Stedman
4.5/5 (790)
STACK&QUEUE
PDF
No ratings yet
STACK&QUEUE
16 pages
Software Engineering-component-of-SRS
PDF
No ratings yet
Software Engineering-component-of-SRS
2 pages
S.Y.B.C.A. Sem-3 - March April - 2019 - Object Oriented Programming
PDF
No ratings yet
S.Y.B.C.A. Sem-3 - March April - 2019 - Object Oriented Programming
3 pages
DFD Examples 1
PDF
No ratings yet
DFD Examples 1
7 pages
S.E Imp Question
PDF
No ratings yet
S.E Imp Question
3 pages
Unit 5
PDF
No ratings yet
Unit 5
8 pages
Web UNIT-1
PDF
No ratings yet
Web UNIT-1
27 pages
Se ch-1
PDF
No ratings yet
Se ch-1
18 pages
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa May Alcott
4/5 (105)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
3.5/5 (109)
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Principles: Life and Work
From Everand
Principles: Life and Work
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Steve Jobs
From Everand
Steve Jobs
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Yes Please
From Everand
Yes Please
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
The Outsider: A Novel
From Everand
The Outsider: A Novel
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Arihant JNV Class 9 Jawahar Navodaya Vidyalaya 2022 Edition
PDF
Arihant JNV Class 9 Jawahar Navodaya Vidyalaya 2022 Edition
John Adams
From Everand
John Adams
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
STACK&QUEUE
PDF
STACK&QUEUE
Software Engineering-component-of-SRS
PDF
Software Engineering-component-of-SRS
S.Y.B.C.A. Sem-3 - March April - 2019 - Object Oriented Programming
PDF
S.Y.B.C.A. Sem-3 - March April - 2019 - Object Oriented Programming
DFD Examples 1
PDF
DFD Examples 1
S.E Imp Question
PDF
S.E Imp Question
Unit 5
PDF
Unit 5
Web UNIT-1
PDF
Web UNIT-1
Se ch-1
PDF
Se ch-1
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
Little Women
From Everand
Little Women
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel