SlideShare a Scribd company logo
1 of 14
Download to read offline
Notes for
SQLite3 Usage
William.L
wiliwe@gmail.com
2014-03-16
Index
Link Error When Building Application with SQLite3 Library ....................................................................... 3
2 forms of LIMIT clause....................................................................................................................................... 4
About sqlite3_get_table()...................................................................................................................................... 5
C Sample Codes..................................................................................................................................................... 7
SQLite Manager (Firefox Add-Ons) ..................................................................................................................11
Link Error When Building Application with SQLite3 Library
When compiling an application which uses SQLite3 library, it might happen “Link Error” that compiler could
not find PThread (POSIX Thread) symbol’s definition as below snapshot.
<Solution>
In the Make file of that application, add Pthread link parameter in GCC built-in Make variable for linker ,
“LDFLAGS”, as below.
$(CC) -o APP $(SRC) $(LDFLAGS)
Or add it in “gcc” command parameter list :
gcc -o APP APP-SRCs -lsqlite3 -lpthread -ISQLite_SRC/.libs
2 forms of LIMIT clause
LIMIT clause is used to limit the data amount returned by the SELECT statement.
There are two equivalent forms of LIMIT :
[Type-1]
LIMIT <skip>, <count>
[Type-2]
LIMIT <count> OFFSET <skip>
Example:
Given 6 records in table “employee” as below.
employee
ID NAME
1 Alice
2 Bob
3 Clyde
4 Derek
5 Eric
6 Fred
If it wants to select 3 records from 2nd position, the statement could be:
SELECT * FROM employee LIMIT 1, 3
or
SELECT * FROM employee LIMIT 3 OFFSET 1
, and its result is :
ID NAME
2 Bob
3 Clyde
4 Derek
.
About sqlite3_get_table()
int sqlite3_get_table(
sqlite3 *db, /* An open database */
const char *zSql, /* SQL to be evaluated */
char ***pazResult, /* Results of the query */
int *pnRow, /* Number of result rows */
int *pnColumn, /* Number of result columns */
char **pzErrmsg /* Error msg written here */
);
The table conceptually has a number of rows and columns. But these numbers are not part of the result table
itself. These numbers are obtained separately.
A result table is an array of pointers to zero-terminated UTF-8 strings.
As an example of the result table format, suppose a query result is as follows:
ID NAME
2 Bob
3 Clyde
4 Derek
.
The content of “pazResult” parameter is as below :
pazResult [0] = "ID";
pazResult [1] = "NAME";
pazResult [2] = "2";
pazResult [3] = "Bob";
pazResult [4] = "3";
pazResult [5] = "Clyde";
pazResult [6] = "4";
pazResult [7] = "Derek";
.
If you want to use 1st field value of 1st record, use this
pazResult[pnColumn]
where “pnColumn” is the number column and this means skipping first “pnColumn” elements of array of result
table and is retrieved through sqlite3_get_table() function. For 2nd field value of 1st record is
pazResult[pnColumn + 1]
Table Headers
1st record
2nd record
3rd record
For 1st field value of 2nd record is
pazResult[pnColumn * 2]
and 2nd field value of 2nd record is
pazResult[pnColumn * 2 + 1]
.
Retrieving other records uses the same rule.
C Sample Codes
<Get Total Number of Records of a Table>
#include <stdlib.h>
#include "sqlite3.h"
/* Macro */
#define SQLite_DBNAME “PathTo/A_SQLite_DB.db”
int GetTotalNumOfRec()
{
/* Variables declaration */
sqlite3 *db = NULL; /* An open database */
char *zErrMsg = NULL; /* Error msg written here */
char **dbResult = NULL; /* Results of the query */
char sqlStmt[512] = {0}; /* Store SQL statement */
int retSql; /* Result of execution of SQL statement. */
int nRow = 0; /* Number of result rows */
int nColumn = 0; /* Number of result columns */
char result[100] = {0}; /* Store the responding message. */
int nRC = 0; /* Record Count in integer type. */
/* Try to connect a SQLite3 database, e,g, a SQLite3 .db file. */
if (sqlite3_open (SQLite_DBNAME, &db) == SQLITE_OK)
{
sprintf(sqlStmt, "SELECT count(*) AS cnt FROM employee;");
retSql = sqlite3_get_table (db, sqlStmt, &dbResult, &nRow, &nColumn, &zErrMsg);
if (retSql != SQLITE_OK)
{
fprintf (stderr, "%s: %s(%d) - SQLite Err [ %s ] n",
__FILE__, __FUNCTION__, __LINE__, zErrMsg);
sqlite3_free (zErrMsg); /* Release memory */
}
else
{
sprintf(result, "%s", dbResult[1]);
nRC = atoi (result); /* convert to integer */
sqlite3_free_table (dbResult); /* Release memory */
sqlite3_close (db); /* Release memory */
return nRC; /* Return amount of records */
}
sqlite3_close (db); /* Release memory */
return 0;
}
else
fprintf(stderr, "%s: %s(%d) - Can Not open SQLite3 database [ %s ] n",
__FILE__, __FUNCTION__, __LINE__, SQLite_DBNAME);
sqlite3_close (db); /* Whether the database is connected successfully or not, it needs to close the
database object for releasing allocated memory. */
return 0;
}
<Iterate Retrieved Records – Type 1>
#include "sqlite3.h"
/* Macro */
#define SQLite_DBNAME “PathTo/A_SQLite_DB.db”
/* Variables declaration */
sqlite3 *db = NULL; /* An open database */
char *zErrMsg = NULL; /* Error msg written here */
char **dbResult = NULL; /* Results of the query */
char sqlStmt[512] = {0}; /* Store SQL statement */
int retSql; /* Result of execution of SQL statement. */
int nRow; /* Number of result rows s */
int nColumn; /* Number of result columns */
/* Try to connect a SQLite3 database, e,g, a SQLite3 .db file. */
if (sqlite3_open(SQLite_DBNAME, &db) == SQLITE_OK)
{
/* select fields “ID” and “NAME” from table “employee” */
sprintf(sqlStmt, "SELECT ID, NAME FROM employee ';");
retSql = sqlite3_get_table (db, sqlStmt, &dbResult, &nRow, &nColumn, &zErrMsg);
if (retSql != SQLITE_OK)
{
fprintf (stderr, "%s: %s(%d) - SQLite Err [ %s ] n", __FILE__, __FUNCTION__, __LINE__, zErrMsg);
sqlite3_free (zErrMsg); /* Release memory */
}
else if( (retSql == SQLITE_OK) && (nRow > 0) )
{
int i;
printf ("%s: %s(%d) - Row [ %d ] n", __FILE__, __FUNCTION__, __LINE__, nRow);
/* Go through all retrieved records */
for(i = 1; i <= nRow; i++)
{
int j;
/* Go through all retrieved records */
for(j = 1; j <= nRow; j++)
printf("%s: %s(%d) – #%d : ID[ %s ] , Name[ %s ] n",
__FILE__, __FUNCTION__, __LINE__,
j, dbResult[nColumn * j], dbResult[nColumn * j + 1]);
} /* end of for( nRow ) */
sqlite3_free_table (dbResult);
} /* end of if( nRow > 0 ) */
else /* nRow == 0 */
sqlite3_free_table (dbResult);
} /* end of if database is connected successfully */
else
fprintf(stderr, "%s: %s(%d) - Can Not open SQLite3 database [ %s ] n",
__FILE__, __FUNCTION__, __LINE__, SQLite_DBNAME);
sqlite3_close (db); /* Whether the database is connected successfully or not, it needs to close the
database object for releasing allocated memory. */
<Iterate Retrieved Records – Type 2 : Using LIMIT Clause >
#include "sqlite3.h"
/* Macro */
#define SQLite_DBNAME “PathTo/A_SQLite_DB.db”
/* Variables declaration */
sqlite3 *db = NULL; /* An open database */
char *zErrMsg = NULL; /* Error msg written here */
char **dbResult = NULL; /* Results of the query */
char sqlStmt[512] = {0}; /* Store SQL statement */
int retSql; /* Result of execution of SQL statement. */
int nRow; /* Number of result rows s */
int nColumn; /* Number of result columns */
/* Try to connect a SQLite3 database, e,g, a SQLite3 .db file. */
if (sqlite3_open(SQLite_DBNAME, &db) == SQLITE_OK)
{
int recCnt = GetTotalNumOfRec(); /* Record Count */
int recNo = 0;
/* Iterate all records */
for(recNo = 0; recNo < recCnt; recNo++)
{
/* select “recNo”nd record from table “employee” */
sprintf(sqlStmt, "SELECT ID, NAME FROM employee LIMIT %d,1;", recNo);
retSql = sqlite3_get_table (db, sqlStmt, &dbResult, &nRow, &nColumn, &zErrMsg);
if (retSql != SQLITE_OK)
{
fprintf (stderr, "%s: %s(%d) - SQLite Err [ %s ] n",
__FILE__, __FUNCTION__, __LINE__, zErrMsg);
sqlite3_free (zErrMsg); /* Release memory */
}
else if( (retSql == SQLITE_OK) && (nRow > 0) )
{
printf("%s: %s(%d) – #%d : ID[ %s ] , Name[ %s ] n",
__FILE__, __FUNCTION__, __LINE__,
recNo, dbResult[nColumn], dbResult[nColumn + 1]);
sqlite3_free_table (dbResult);
} /* end of if( nRow > 0 ) */
else /* nRow == 0 */
sqlite3_free_table (dbResult);
} /* end of for(recNo) */
} /* end of if database is connected successfully */
else
fprintf(stderr, "%s: %s(%d) - Can Not open SQLite3 database [ %s ] n",
__FILE__, __FUNCTION__, __LINE__, SQLite_DBNAME);
sqlite3_close (db); /* Whether the database is connected successfully or not, it needs to close the
database object for releasing allocated memory. */
SQLite Manager (Firefox Add-Ons)
1. Download and install the latest Firefox web browser
2. Open Firefox and connet this site
https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/
3. Click button to download and install SQLite Manager add-on
4. After installation, invoke SQLite Manager by click menu “Tools -> SQLite Manager”
5. SQLite Manager window is as below.
In SQLite Manager, click “Database -> Connect Database” menu to open File Dialog and locate the SQLite
database file you want to open.
When opening a SQLite database, it would be below screens.
If you want to close the opened database, by clicking “Database -> Close Database” menu.
View
tables
View table’s
schema
View records of
speicified table
It can change field’s
property by right click
and click “Edit” item
It can modify value of
fields of one record by
by right click and click
“Edit” item
Notes for SQLite3 Usage

More Related Content

What's hot

R57shell
R57shellR57shell
R57shell
ady36
 
Pontos para criar_instancia_data guard_11g
Pontos para criar_instancia_data guard_11gPontos para criar_instancia_data guard_11g
Pontos para criar_instancia_data guard_11g
Leandro Santos
 
11 Things About 11gr2
11 Things About 11gr211 Things About 11gr2
11 Things About 11gr2
afa reg
 

What's hot (16)

C99
C99C99
C99
 
dcs plus Catalogue 2015
dcs plus Catalogue 2015dcs plus Catalogue 2015
dcs plus Catalogue 2015
 
SAS codes and tricks Comprehensive all codes
SAS codes and tricks Comprehensive all codesSAS codes and tricks Comprehensive all codes
SAS codes and tricks Comprehensive all codes
 
SAS codes and tricks Comprehensive all codess
SAS codes and tricks Comprehensive all codessSAS codes and tricks Comprehensive all codess
SAS codes and tricks Comprehensive all codess
 
My All Codes of SAS
My All Codes of SASMy All Codes of SAS
My All Codes of SAS
 
R57shell
R57shellR57shell
R57shell
 
Deber base
Deber baseDeber base
Deber base
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
Pontos para criar_instancia_data guard_11g
Pontos para criar_instancia_data guard_11gPontos para criar_instancia_data guard_11g
Pontos para criar_instancia_data guard_11g
 
Extbase and Beyond
Extbase and BeyondExtbase and Beyond
Extbase and Beyond
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code Review
 
11 Things About 11gr2
11 Things About 11gr211 Things About 11gr2
11 Things About 11gr2
 
C99[2]
C99[2]C99[2]
C99[2]
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find Fraudsters
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
 
Spss syntax
Spss syntaxSpss syntax
Spss syntax
 

Similar to Notes for SQLite3 Usage

finalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the bfinalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
ChereCheek752
 
Wait Events 10g
Wait Events 10gWait Events 10g
Wait Events 10g
sagai
 
Hacking Parse.y with ujihisa
Hacking Parse.y with ujihisaHacking Parse.y with ujihisa
Hacking Parse.y with ujihisa
ujihisa
 
Password protected personal diary report
Password protected personal diary reportPassword protected personal diary report
Password protected personal diary report
Moueed Ahmed
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
Reka
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
Joe Jiang
 
Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)
ujihisa
 
Yy
YyYy
Yy
yygh
 

Similar to Notes for SQLite3 Usage (20)

FMDB - SLC-Cocoaheads
FMDB - SLC-CocoaheadsFMDB - SLC-Cocoaheads
FMDB - SLC-Cocoaheads
 
sas aeroplan sample
sas aeroplan samplesas aeroplan sample
sas aeroplan sample
 
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the bfinalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
finalprojtemplatev5finalprojtemplate.gitignore# Ignore the b
 
Wait Events 10g
Wait Events 10gWait Events 10g
Wait Events 10g
 
Memory Manglement in Raku
Memory Manglement in RakuMemory Manglement in Raku
Memory Manglement in Raku
 
groovy databases
groovy databasesgroovy databases
groovy databases
 
Vcs16
Vcs16Vcs16
Vcs16
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Hacking Parse.y with ujihisa
Hacking Parse.y with ujihisaHacking Parse.y with ujihisa
Hacking Parse.y with ujihisa
 
Password protected personal diary report
Password protected personal diary reportPassword protected personal diary report
Password protected personal diary report
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Go Says WAT?
Go Says WAT?Go Says WAT?
Go Says WAT?
 
Week 12 code
Week 12 codeWeek 12 code
Week 12 code
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)Hacking parse.y (RubyKansai38)
Hacking parse.y (RubyKansai38)
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
Yy
YyYy
Yy
 
Having Fun Programming!
Having Fun Programming!Having Fun Programming!
Having Fun Programming!
 
C SQLite usage
C SQLite usageC SQLite usage
C SQLite usage
 

More from William Lee

More from William Lee (20)

Usage Note of Apache Thrift for C++ Java PHP Languages
Usage Note of Apache Thrift for C++ Java PHP LanguagesUsage Note of Apache Thrift for C++ Java PHP Languages
Usage Note of Apache Thrift for C++ Java PHP Languages
 
Usage Note of Qt ODBC Database Access on Linux
Usage Note of Qt ODBC Database Access on LinuxUsage Note of Qt ODBC Database Access on Linux
Usage Note of Qt ODBC Database Access on Linux
 
Usage Note of SWIG for PHP
Usage Note of SWIG for PHPUsage Note of SWIG for PHP
Usage Note of SWIG for PHP
 
Upgrade GCC & Install Qt 5.4 on CentOS 6.5
Upgrade GCC & Install Qt 5.4 on CentOS 6.5 Upgrade GCC & Install Qt 5.4 on CentOS 6.5
Upgrade GCC & Install Qt 5.4 on CentOS 6.5
 
Usage Notes of The Bro 2.2 / 2.3
Usage Notes of The Bro 2.2 / 2.3Usage Notes of The Bro 2.2 / 2.3
Usage Notes of The Bro 2.2 / 2.3
 
Viewing Android Source Files in Eclipse (Chinese)
Viewing Android Source Files in Eclipse  (Chinese)Viewing Android Source Files in Eclipse  (Chinese)
Viewing Android Source Files in Eclipse (Chinese)
 
Usage Note of Microsoft Dependency Walker
Usage Note of Microsoft Dependency WalkerUsage Note of Microsoft Dependency Walker
Usage Note of Microsoft Dependency Walker
 
Usage Note of PlayCap
Usage Note of PlayCapUsage Note of PlayCap
Usage Note of PlayCap
 
Qt4 App - Sliding Window
Qt4 App - Sliding WindowQt4 App - Sliding Window
Qt4 App - Sliding Window
 
GTK+ 2.0 App - Desktop App Chooser
GTK+ 2.0 App - Desktop App ChooserGTK+ 2.0 App - Desktop App Chooser
GTK+ 2.0 App - Desktop App Chooser
 
GTK+ 2.0 App - Icon Chooser
GTK+ 2.0 App - Icon ChooserGTK+ 2.0 App - Icon Chooser
GTK+ 2.0 App - Icon Chooser
 
Note of CGI and ASP
Note of CGI and ASPNote of CGI and ASP
Note of CGI and ASP
 
Moblin2 - Window Manager(Mutter) Plugin
Moblin2 - Window Manager(Mutter) PluginMoblin2 - Window Manager(Mutter) Plugin
Moblin2 - Window Manager(Mutter) Plugin
 
MGCP Overview
MGCP OverviewMGCP Overview
MGCP Overview
 
Asterisk (IP-PBX) CDR Log Rotation
Asterisk (IP-PBX) CDR Log RotationAsterisk (IP-PBX) CDR Log Rotation
Asterisk (IP-PBX) CDR Log Rotation
 
L.A.M.P Installation Note --- CentOS 6.5
L.A.M.P Installation Note --- CentOS 6.5L.A.M.P Installation Note --- CentOS 6.5
L.A.M.P Installation Note --- CentOS 6.5
 
C Program Runs on Wrong Target Platform(CPU Architecture)
C Program Runs on Wrong Target Platform(CPU Architecture)C Program Runs on Wrong Target Platform(CPU Architecture)
C Program Runs on Wrong Target Platform(CPU Architecture)
 
Internationalization(i18n) of Web Page
Internationalization(i18n) of Web PageInternationalization(i18n) of Web Page
Internationalization(i18n) of Web Page
 
Cygwin Install How-To (Chinese)
Cygwin Install How-To (Chinese)Cygwin Install How-To (Chinese)
Cygwin Install How-To (Chinese)
 
Android Storage - StorageManager & OBB
Android Storage - StorageManager & OBBAndroid Storage - StorageManager & OBB
Android Storage - StorageManager & OBB
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

Notes for SQLite3 Usage

  • 2. Index Link Error When Building Application with SQLite3 Library ....................................................................... 3 2 forms of LIMIT clause....................................................................................................................................... 4 About sqlite3_get_table()...................................................................................................................................... 5 C Sample Codes..................................................................................................................................................... 7 SQLite Manager (Firefox Add-Ons) ..................................................................................................................11
  • 3. Link Error When Building Application with SQLite3 Library When compiling an application which uses SQLite3 library, it might happen “Link Error” that compiler could not find PThread (POSIX Thread) symbol’s definition as below snapshot. <Solution> In the Make file of that application, add Pthread link parameter in GCC built-in Make variable for linker , “LDFLAGS”, as below. $(CC) -o APP $(SRC) $(LDFLAGS) Or add it in “gcc” command parameter list : gcc -o APP APP-SRCs -lsqlite3 -lpthread -ISQLite_SRC/.libs
  • 4. 2 forms of LIMIT clause LIMIT clause is used to limit the data amount returned by the SELECT statement. There are two equivalent forms of LIMIT : [Type-1] LIMIT <skip>, <count> [Type-2] LIMIT <count> OFFSET <skip> Example: Given 6 records in table “employee” as below. employee ID NAME 1 Alice 2 Bob 3 Clyde 4 Derek 5 Eric 6 Fred If it wants to select 3 records from 2nd position, the statement could be: SELECT * FROM employee LIMIT 1, 3 or SELECT * FROM employee LIMIT 3 OFFSET 1 , and its result is : ID NAME 2 Bob 3 Clyde 4 Derek .
  • 5. About sqlite3_get_table() int sqlite3_get_table( sqlite3 *db, /* An open database */ const char *zSql, /* SQL to be evaluated */ char ***pazResult, /* Results of the query */ int *pnRow, /* Number of result rows */ int *pnColumn, /* Number of result columns */ char **pzErrmsg /* Error msg written here */ ); The table conceptually has a number of rows and columns. But these numbers are not part of the result table itself. These numbers are obtained separately. A result table is an array of pointers to zero-terminated UTF-8 strings. As an example of the result table format, suppose a query result is as follows: ID NAME 2 Bob 3 Clyde 4 Derek . The content of “pazResult” parameter is as below : pazResult [0] = "ID"; pazResult [1] = "NAME"; pazResult [2] = "2"; pazResult [3] = "Bob"; pazResult [4] = "3"; pazResult [5] = "Clyde"; pazResult [6] = "4"; pazResult [7] = "Derek"; . If you want to use 1st field value of 1st record, use this pazResult[pnColumn] where “pnColumn” is the number column and this means skipping first “pnColumn” elements of array of result table and is retrieved through sqlite3_get_table() function. For 2nd field value of 1st record is pazResult[pnColumn + 1] Table Headers 1st record 2nd record 3rd record
  • 6. For 1st field value of 2nd record is pazResult[pnColumn * 2] and 2nd field value of 2nd record is pazResult[pnColumn * 2 + 1] . Retrieving other records uses the same rule.
  • 7. C Sample Codes <Get Total Number of Records of a Table> #include <stdlib.h> #include "sqlite3.h" /* Macro */ #define SQLite_DBNAME “PathTo/A_SQLite_DB.db” int GetTotalNumOfRec() { /* Variables declaration */ sqlite3 *db = NULL; /* An open database */ char *zErrMsg = NULL; /* Error msg written here */ char **dbResult = NULL; /* Results of the query */ char sqlStmt[512] = {0}; /* Store SQL statement */ int retSql; /* Result of execution of SQL statement. */ int nRow = 0; /* Number of result rows */ int nColumn = 0; /* Number of result columns */ char result[100] = {0}; /* Store the responding message. */ int nRC = 0; /* Record Count in integer type. */ /* Try to connect a SQLite3 database, e,g, a SQLite3 .db file. */ if (sqlite3_open (SQLite_DBNAME, &db) == SQLITE_OK) { sprintf(sqlStmt, "SELECT count(*) AS cnt FROM employee;"); retSql = sqlite3_get_table (db, sqlStmt, &dbResult, &nRow, &nColumn, &zErrMsg); if (retSql != SQLITE_OK) { fprintf (stderr, "%s: %s(%d) - SQLite Err [ %s ] n", __FILE__, __FUNCTION__, __LINE__, zErrMsg); sqlite3_free (zErrMsg); /* Release memory */ } else { sprintf(result, "%s", dbResult[1]); nRC = atoi (result); /* convert to integer */ sqlite3_free_table (dbResult); /* Release memory */ sqlite3_close (db); /* Release memory */
  • 8. return nRC; /* Return amount of records */ } sqlite3_close (db); /* Release memory */ return 0; } else fprintf(stderr, "%s: %s(%d) - Can Not open SQLite3 database [ %s ] n", __FILE__, __FUNCTION__, __LINE__, SQLite_DBNAME); sqlite3_close (db); /* Whether the database is connected successfully or not, it needs to close the database object for releasing allocated memory. */ return 0; } <Iterate Retrieved Records – Type 1> #include "sqlite3.h" /* Macro */ #define SQLite_DBNAME “PathTo/A_SQLite_DB.db” /* Variables declaration */ sqlite3 *db = NULL; /* An open database */ char *zErrMsg = NULL; /* Error msg written here */ char **dbResult = NULL; /* Results of the query */ char sqlStmt[512] = {0}; /* Store SQL statement */ int retSql; /* Result of execution of SQL statement. */ int nRow; /* Number of result rows s */ int nColumn; /* Number of result columns */ /* Try to connect a SQLite3 database, e,g, a SQLite3 .db file. */ if (sqlite3_open(SQLite_DBNAME, &db) == SQLITE_OK) { /* select fields “ID” and “NAME” from table “employee” */ sprintf(sqlStmt, "SELECT ID, NAME FROM employee ';"); retSql = sqlite3_get_table (db, sqlStmt, &dbResult, &nRow, &nColumn, &zErrMsg); if (retSql != SQLITE_OK) { fprintf (stderr, "%s: %s(%d) - SQLite Err [ %s ] n", __FILE__, __FUNCTION__, __LINE__, zErrMsg); sqlite3_free (zErrMsg); /* Release memory */
  • 9. } else if( (retSql == SQLITE_OK) && (nRow > 0) ) { int i; printf ("%s: %s(%d) - Row [ %d ] n", __FILE__, __FUNCTION__, __LINE__, nRow); /* Go through all retrieved records */ for(i = 1; i <= nRow; i++) { int j; /* Go through all retrieved records */ for(j = 1; j <= nRow; j++) printf("%s: %s(%d) – #%d : ID[ %s ] , Name[ %s ] n", __FILE__, __FUNCTION__, __LINE__, j, dbResult[nColumn * j], dbResult[nColumn * j + 1]); } /* end of for( nRow ) */ sqlite3_free_table (dbResult); } /* end of if( nRow > 0 ) */ else /* nRow == 0 */ sqlite3_free_table (dbResult); } /* end of if database is connected successfully */ else fprintf(stderr, "%s: %s(%d) - Can Not open SQLite3 database [ %s ] n", __FILE__, __FUNCTION__, __LINE__, SQLite_DBNAME); sqlite3_close (db); /* Whether the database is connected successfully or not, it needs to close the database object for releasing allocated memory. */ <Iterate Retrieved Records – Type 2 : Using LIMIT Clause > #include "sqlite3.h" /* Macro */ #define SQLite_DBNAME “PathTo/A_SQLite_DB.db” /* Variables declaration */ sqlite3 *db = NULL; /* An open database */ char *zErrMsg = NULL; /* Error msg written here */ char **dbResult = NULL; /* Results of the query */ char sqlStmt[512] = {0}; /* Store SQL statement */
  • 10. int retSql; /* Result of execution of SQL statement. */ int nRow; /* Number of result rows s */ int nColumn; /* Number of result columns */ /* Try to connect a SQLite3 database, e,g, a SQLite3 .db file. */ if (sqlite3_open(SQLite_DBNAME, &db) == SQLITE_OK) { int recCnt = GetTotalNumOfRec(); /* Record Count */ int recNo = 0; /* Iterate all records */ for(recNo = 0; recNo < recCnt; recNo++) { /* select “recNo”nd record from table “employee” */ sprintf(sqlStmt, "SELECT ID, NAME FROM employee LIMIT %d,1;", recNo); retSql = sqlite3_get_table (db, sqlStmt, &dbResult, &nRow, &nColumn, &zErrMsg); if (retSql != SQLITE_OK) { fprintf (stderr, "%s: %s(%d) - SQLite Err [ %s ] n", __FILE__, __FUNCTION__, __LINE__, zErrMsg); sqlite3_free (zErrMsg); /* Release memory */ } else if( (retSql == SQLITE_OK) && (nRow > 0) ) { printf("%s: %s(%d) – #%d : ID[ %s ] , Name[ %s ] n", __FILE__, __FUNCTION__, __LINE__, recNo, dbResult[nColumn], dbResult[nColumn + 1]); sqlite3_free_table (dbResult); } /* end of if( nRow > 0 ) */ else /* nRow == 0 */ sqlite3_free_table (dbResult); } /* end of for(recNo) */ } /* end of if database is connected successfully */ else fprintf(stderr, "%s: %s(%d) - Can Not open SQLite3 database [ %s ] n", __FILE__, __FUNCTION__, __LINE__, SQLite_DBNAME); sqlite3_close (db); /* Whether the database is connected successfully or not, it needs to close the database object for releasing allocated memory. */
  • 11. SQLite Manager (Firefox Add-Ons) 1. Download and install the latest Firefox web browser 2. Open Firefox and connet this site https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/ 3. Click button to download and install SQLite Manager add-on 4. After installation, invoke SQLite Manager by click menu “Tools -> SQLite Manager”
  • 12. 5. SQLite Manager window is as below. In SQLite Manager, click “Database -> Connect Database” menu to open File Dialog and locate the SQLite database file you want to open.
  • 13. When opening a SQLite database, it would be below screens. If you want to close the opened database, by clicking “Database -> Close Database” menu. View tables View table’s schema View records of speicified table It can change field’s property by right click and click “Edit” item It can modify value of fields of one record by by right click and click “Edit” item