SlideShare a Scribd company logo
1 of 20
Download to read offline
SQLite usage
SQLite
● Good
○ File based
○ Development
○ Small
● Bad
○ No ACL
○ Performance
○ Alow only one write at a time
SQLite Flow
● Create DB/table/index
● Prepare SQL
● SQL bind
● SQL Query
Create DB/table/index
#define CMD_CREATE_DP_TABLE "CREATE TABLE IF NOT EXISTS `data_planner` (" 
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," 
"`tx_bytes` bigint(20) NOT NULL," 
"`rx_bytes` bigint(20) NOT NULL," 
"`timestamp` datetime);"
#define CMD_CREATE_DP_INDEX "CREATE INDEX IF NOT EXISTS `timestamp_idx` ON 
`data_planner` (`timestamp` DESC);"
Create DB/table/index
sqlite3 *db = NULL;
char *err_msg = NULL;
int ret = -1;
if (sqlite3_open(DATA_PLANNER_DB_PATH, &db) != SQLITE_OK) {
syslog(LOG_ERR, "Open sqlite fail: %s", DATA_PLANNER_DB_PATH);
goto out;
}
if (sqlite3_exec(db, CMD_CREATE_DP_TABLE, NULL, NULL, &err_msg) != SQLITE_OK) {
syslog(LOG_ERR, "Create data_planner table fail: %s", err_msg);
goto out;
}
if (err_msg) sqlite3_free(err_msg);
Create DB/table/index
if (sqlite3_exec(db, CMD_CREATE_DP_INDEX, NULL, NULL, &err_msg) != SQLITE_OK) {
syslog(LOG_ERR, "Create data_planner index fail: %s", err_msg);
goto out;
}
ret = 0;
out:
if (err_msg) sqlite3_free(err_msg);
if (db) sqlite3_close(db);
return ret;
Create DB/table/index
● Check if using index
● “EXPLAIN <your query>”
○ ex: EXPLAIN SELECT * FROM a WERHE name =
“1”;
○ Will show IdxRowid/IdxGE if apply index
Create DB/table/index
sqlite> explain select * from users where name='foo';
0|Trace|0|0|0||00|
1|String8|0|1|0|foo|00|
2|Goto|0|18|0||00|
3|OpenRead|0|2|0|2|00|
4|OpenRead|1|3|0|keyinfo(1,BINARY)|00|
5|IsNull|1|15|0||00|
6|Affinity|1|1|0|bb|00|
7|SeekGe|1|15|1|1|00|
8|IdxGE|1|15|1|1|01|
9|IdxRowid|1|2|0||00|
...blahblah
21|Goto|0|3|0||00|
Create DB/table/index
● When to create?
○ System startup
○ Program startup
○ In every query
Prepare SQL
sqlite3 *db = NULL;
sqlite3_stmt *stmt = NULL;
int ret = DP_ERROR;
if (sqlite3_open(DATA_PLANNER_DB_PATH, &db) != SQLITE_OK) {
syslog(LOG_ERR, "Open sqlite fail: %s", DATA_PLANNER_DB_PATH);
goto out;
}
char *sql = "SELECT sum(tx_bytes) as total_tx_bytes,sum(rx_bytes) as total_rx_bytes 
FROM data_planner WHERE datetime(timestamp, 'localtime') >= ? AND datetime(timestamp, 'localtime') < ?;";
if (sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, NULL) != SQLITE_OK) {
syslog(LOG_ERR, "SQL prepare fail: %s", sql);
goto out;
}
SQL Bind
sqlite3_bind_text(stmt, 1, begin_date, -1, NULL);
sqlite3_bind_text(stmt, 2, end_date, -1, NULL);
// Also, there is no uint64, only int64
SQL Query
if (sqlite3_step(stmt) == SQLITE_ROW) {
*total_tx_bytes = sqlite3_column_int64(stmt, 0);
*total_rx_bytes = sqlite3_column_int64(stmt, 1);
} else {
syslog(LOG_ERR, "SQL fail: Error when get previous total data: %s", sqlite3_errmsg(db));
goto out;
}
ret = 0;
out:
if (stmt) sqlite3_finalize(stmt);
if (db) sqlite3_close(db);
return ret;
SQL Query
● sqlite3_exec
○ sqlite3_prepare_v2 + sqlite3_step + sqlite3_finalize
○ Good for insertion/create table/transaction
○ Bad for query
SQL Query
sqlite3_exec(
sqlite3*,
const char *sql,
int (*callback)(void*, int column_num, char**, char**),
void *,
char **errmsg
}
// void * is for user data
Timezone issue
● Use UTC
● In C
○ Use gmtime_r instead of localtime_r
● In SQLite3
○ Insert using datetime(?, 'unixepoch')
■ ? is time_t
○ Query using datetime(timestamp, 'localtime')
SQL Debug
void* sqlite3_trace( sqlite3* db, trace_callback, void* udp);
// Register sql callback and call it every time before executing
void trace_callback( void* udp, const char* sql );
// udp means user data pointer
SQLite Busy Handle
● SQlite may be locked sometimes, solution:
○ sqlite3_busy_handle
■ More flexible, can add sleep() and retry times
○ sqlite3_busy_timeout
○ http://www.bubuko.com/infodetail-240892.html
○ http://www.360doc.
com/content/10/1214/12/87000_77984300.shtml
Relational Database
● MariaDB/MySQL/Percona
○ Multiple engines
■ MyISAM
● Table lock
■ InnoDB
● Row lock
● Transaction
● PostgreSQL
● SQLite
Relational Database
● Replication
○ For read
○ Master/Slave
● Sharding
○ For read/write
○ Do not rely on auto sharding
Reference
● http://stackoverflow.com/questions/1454188/how-can-i-analyse-a-sqlite-query-execution
● https://www.sqlite.org/docs.html
● http://www.cnblogs.com/likebeta/archive/2012/06/17/2552757.html

More Related Content

What's hot

Scaling MongoDB; Sharding Into and Beyond the Multi-Terabyte Range
Scaling MongoDB; Sharding Into and Beyond the Multi-Terabyte RangeScaling MongoDB; Sharding Into and Beyond the Multi-Terabyte Range
Scaling MongoDB; Sharding Into and Beyond the Multi-Terabyte RangeMongoDB
 
jQuery Datatables With MongDb
jQuery Datatables With MongDbjQuery Datatables With MongDb
jQuery Datatables With MongDbsliimohara
 
Александр Терещук - Memory Analyzer Tool and memory optimization tips in Android
Александр Терещук - Memory Analyzer Tool and memory optimization tips in AndroidАлександр Терещук - Memory Analyzer Tool and memory optimization tips in Android
Александр Терещук - Memory Analyzer Tool and memory optimization tips in AndroidUA Mobile
 
Node.js and angular js
Node.js and angular jsNode.js and angular js
Node.js and angular jsHyungKuIm
 
Afte DDL on Database PL/SQL Code
Afte DDL on Database PL/SQL CodeAfte DDL on Database PL/SQL Code
Afte DDL on Database PL/SQL CodeAnar Godjaev
 
Bangun datar dan bangun ruang
Bangun datar dan bangun ruangBangun datar dan bangun ruang
Bangun datar dan bangun ruangSanSan Yagyoo
 
MobileCity:Core Data
MobileCity:Core DataMobileCity:Core Data
MobileCity:Core DataAllan Davis
 
Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin
Get the Most Out of iOS 11 with Visual Studio Tools for XamarinGet the Most Out of iOS 11 with Visual Studio Tools for Xamarin
Get the Most Out of iOS 11 with Visual Studio Tools for XamarinXamarin
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveEugene Zharkov
 
Flutter Reactive Programming 介紹 - part 1 (Stream)
Flutter Reactive Programming 介紹 - part 1 (Stream)Flutter Reactive Programming 介紹 - part 1 (Stream)
Flutter Reactive Programming 介紹 - part 1 (Stream)振揚 陳
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptCaridy Patino
 
Connectivity coding for java and mysql
Connectivity coding for java and mysqlConnectivity coding for java and mysql
Connectivity coding for java and mysqlFahad Ali Khan
 
Understanding Functions and "this" in the World of ES2017+
Understanding Functions and "this" in the World of ES2017+Understanding Functions and "this" in the World of ES2017+
Understanding Functions and "this" in the World of ES2017+Bryan Hughes
 

What's hot (20)

Scaling MongoDB; Sharding Into and Beyond the Multi-Terabyte Range
Scaling MongoDB; Sharding Into and Beyond the Multi-Terabyte RangeScaling MongoDB; Sharding Into and Beyond the Multi-Terabyte Range
Scaling MongoDB; Sharding Into and Beyond the Multi-Terabyte Range
 
jQuery Datatables With MongDb
jQuery Datatables With MongDbjQuery Datatables With MongDb
jQuery Datatables With MongDb
 
Александр Терещук - Memory Analyzer Tool and memory optimization tips in Android
Александр Терещук - Memory Analyzer Tool and memory optimization tips in AndroidАлександр Терещук - Memory Analyzer Tool and memory optimization tips in Android
Александр Терещук - Memory Analyzer Tool and memory optimization tips in Android
 
greenDAO
greenDAOgreenDAO
greenDAO
 
jQuery's Secrets
jQuery's SecretsjQuery's Secrets
jQuery's Secrets
 
Node.js and angular js
Node.js and angular jsNode.js and angular js
Node.js and angular js
 
Green dao
Green daoGreen dao
Green dao
 
Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0
 
Afte DDL on Database PL/SQL Code
Afte DDL on Database PL/SQL CodeAfte DDL on Database PL/SQL Code
Afte DDL on Database PL/SQL Code
 
Bangun datar dan bangun ruang
Bangun datar dan bangun ruangBangun datar dan bangun ruang
Bangun datar dan bangun ruang
 
MobileCity:Core Data
MobileCity:Core DataMobileCity:Core Data
MobileCity:Core Data
 
Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin
Get the Most Out of iOS 11 with Visual Studio Tools for XamarinGet the Most Out of iOS 11 with Visual Studio Tools for Xamarin
Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin
 
Cycle.js: Functional and Reactive
Cycle.js: Functional and ReactiveCycle.js: Functional and Reactive
Cycle.js: Functional and Reactive
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Ricky Bobby's World
Ricky Bobby's WorldRicky Bobby's World
Ricky Bobby's World
 
Flutter Reactive Programming 介紹 - part 1 (Stream)
Flutter Reactive Programming 介紹 - part 1 (Stream)Flutter Reactive Programming 介紹 - part 1 (Stream)
Flutter Reactive Programming 介紹 - part 1 (Stream)
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScript
 
Connectivity coding for java and mysql
Connectivity coding for java and mysqlConnectivity coding for java and mysql
Connectivity coding for java and mysql
 
Understanding Functions and "this" in the World of ES2017+
Understanding Functions and "this" in the World of ES2017+Understanding Functions and "this" in the World of ES2017+
Understanding Functions and "this" in the World of ES2017+
 
MongoDB Oplog入門
MongoDB Oplog入門MongoDB Oplog入門
MongoDB Oplog入門
 

Viewers also liked

Sync It Up
Sync It UpSync It Up
Sync It Upsvoisen
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniquesjoaopmaia
 
EDDI 2011 - A Generic Multilevel Approach for Designing Domain Ontologies Bas...
EDDI 2011 - A Generic Multilevel Approach for Designing Domain Ontologies Bas...EDDI 2011 - A Generic Multilevel Approach for Designing Domain Ontologies Bas...
EDDI 2011 - A Generic Multilevel Approach for Designing Domain Ontologies Bas...Dr.-Ing. Thomas Hartmann
 
Data sync on iOS with Couchbase Mobile
Data sync on iOS with Couchbase MobileData sync on iOS with Couchbase Mobile
Data sync on iOS with Couchbase MobileThiago Alencar
 
Integrating a Domain Ontology Development Environment and an Ontology Search ...
Integrating a Domain Ontology Development Environment and an Ontology Search ...Integrating a Domain Ontology Development Environment and an Ontology Search ...
Integrating a Domain Ontology Development Environment and an Ontology Search ...Takeshi Morita
 
C++ и базы данных
C++ и базы данныхC++ и базы данных
C++ и базы данныхmcroitor
 
MySQL Group Replication
MySQL Group ReplicationMySQL Group Replication
MySQL Group ReplicationUlf Wendel
 

Viewers also liked (7)

Sync It Up
Sync It UpSync It Up
Sync It Up
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
 
EDDI 2011 - A Generic Multilevel Approach for Designing Domain Ontologies Bas...
EDDI 2011 - A Generic Multilevel Approach for Designing Domain Ontologies Bas...EDDI 2011 - A Generic Multilevel Approach for Designing Domain Ontologies Bas...
EDDI 2011 - A Generic Multilevel Approach for Designing Domain Ontologies Bas...
 
Data sync on iOS with Couchbase Mobile
Data sync on iOS with Couchbase MobileData sync on iOS with Couchbase Mobile
Data sync on iOS with Couchbase Mobile
 
Integrating a Domain Ontology Development Environment and an Ontology Search ...
Integrating a Domain Ontology Development Environment and an Ontology Search ...Integrating a Domain Ontology Development Environment and an Ontology Search ...
Integrating a Domain Ontology Development Environment and an Ontology Search ...
 
C++ и базы данных
C++ и базы данныхC++ и базы данных
C++ и базы данных
 
MySQL Group Replication
MySQL Group ReplicationMySQL Group Replication
MySQL Group Replication
 

Similar to C SQLite usage

DEF CON 27 -OMER GULL - select code execution from using sq lite
DEF CON 27 -OMER GULL - select code execution from using sq liteDEF CON 27 -OMER GULL - select code execution from using sq lite
DEF CON 27 -OMER GULL - select code execution from using sq liteFelipe Prado
 
Notes for SQLite3 Usage
Notes for SQLite3 UsageNotes for SQLite3 Usage
Notes for SQLite3 UsageWilliam Lee
 
Asegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingAsegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingChema Alonso
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)Craig Dickson
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Databasejitendral
 
Oracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the IndicesOracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the IndicesKellyn Pot'Vin-Gorman
 
Bkbiet day2 & 3
Bkbiet day2 & 3Bkbiet day2 & 3
Bkbiet day2 & 3mihirio
 
SequoiaDB Distributed Relational Database
SequoiaDB Distributed Relational DatabaseSequoiaDB Distributed Relational Database
SequoiaDB Distributed Relational Databasewangzhonnew
 
How do I draw the Labview code for pneumatic cylinder(air pistion). .pdf
How do I draw the Labview code for pneumatic cylinder(air pistion). .pdfHow do I draw the Labview code for pneumatic cylinder(air pistion). .pdf
How do I draw the Labview code for pneumatic cylinder(air pistion). .pdffootstatus
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRPeter Elst
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
Работа с реляционными базами данных в C++
Работа с реляционными базами данных в C++Работа с реляционными базами данных в C++
Работа с реляционными базами данных в C++corehard_by
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationBartosz Konieczny
 
10 Key MongoDB Performance Indicators
10 Key MongoDB Performance Indicators  10 Key MongoDB Performance Indicators
10 Key MongoDB Performance Indicators iammutex
 
ShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlChema Alonso
 
11 Things About11g
11 Things About11g11 Things About11g
11 Things About11gfcamachob
 
11thingsabout11g 12659705398222 Phpapp01
11thingsabout11g 12659705398222 Phpapp0111thingsabout11g 12659705398222 Phpapp01
11thingsabout11g 12659705398222 Phpapp01Karam Abuataya
 

Similar to C SQLite usage (20)

DEF CON 27 -OMER GULL - select code execution from using sq lite
DEF CON 27 -OMER GULL - select code execution from using sq liteDEF CON 27 -OMER GULL - select code execution from using sq lite
DEF CON 27 -OMER GULL - select code execution from using sq lite
 
Employ leave dtb
Employ leave dtbEmploy leave dtb
Employ leave dtb
 
Notes for SQLite3 Usage
Notes for SQLite3 UsageNotes for SQLite3 Usage
Notes for SQLite3 Usage
 
Asegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File DownloadingAsegúr@IT IV - Remote File Downloading
Asegúr@IT IV - Remote File Downloading
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Oracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the IndicesOracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the Indices
 
Orasta500.c
Orasta500.cOrasta500.c
Orasta500.c
 
Bkbiet day2 & 3
Bkbiet day2 & 3Bkbiet day2 & 3
Bkbiet day2 & 3
 
SequoiaDB Distributed Relational Database
SequoiaDB Distributed Relational DatabaseSequoiaDB Distributed Relational Database
SequoiaDB Distributed Relational Database
 
How do I draw the Labview code for pneumatic cylinder(air pistion). .pdf
How do I draw the Labview code for pneumatic cylinder(air pistion). .pdfHow do I draw the Labview code for pneumatic cylinder(air pistion). .pdf
How do I draw the Labview code for pneumatic cylinder(air pistion). .pdf
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIR
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Работа с реляционными базами данных в C++
Работа с реляционными базами данных в C++Работа с реляционными базами данных в C++
Работа с реляционными базами данных в C++
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customization
 
10 Key MongoDB Performance Indicators
10 Key MongoDB Performance Indicators  10 Key MongoDB Performance Indicators
10 Key MongoDB Performance Indicators
 
ShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)Sql
 
11 Things About11g
11 Things About11g11 Things About11g
11 Things About11g
 
11thingsabout11g 12659705398222 Phpapp01
11thingsabout11g 12659705398222 Phpapp0111thingsabout11g 12659705398222 Phpapp01
11thingsabout11g 12659705398222 Phpapp01
 

Recently uploaded

TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptNarmatha D
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxVelmuruganTECE
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESNarmatha D
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdfCaalaaAbdulkerim
 

Recently uploaded (20)

TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.ppt
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptx
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIES
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdf
 

C SQLite usage

  • 2. SQLite ● Good ○ File based ○ Development ○ Small ● Bad ○ No ACL ○ Performance ○ Alow only one write at a time
  • 3. SQLite Flow ● Create DB/table/index ● Prepare SQL ● SQL bind ● SQL Query
  • 4. Create DB/table/index #define CMD_CREATE_DP_TABLE "CREATE TABLE IF NOT EXISTS `data_planner` (" "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," "`tx_bytes` bigint(20) NOT NULL," "`rx_bytes` bigint(20) NOT NULL," "`timestamp` datetime);" #define CMD_CREATE_DP_INDEX "CREATE INDEX IF NOT EXISTS `timestamp_idx` ON `data_planner` (`timestamp` DESC);"
  • 5. Create DB/table/index sqlite3 *db = NULL; char *err_msg = NULL; int ret = -1; if (sqlite3_open(DATA_PLANNER_DB_PATH, &db) != SQLITE_OK) { syslog(LOG_ERR, "Open sqlite fail: %s", DATA_PLANNER_DB_PATH); goto out; } if (sqlite3_exec(db, CMD_CREATE_DP_TABLE, NULL, NULL, &err_msg) != SQLITE_OK) { syslog(LOG_ERR, "Create data_planner table fail: %s", err_msg); goto out; } if (err_msg) sqlite3_free(err_msg);
  • 6. Create DB/table/index if (sqlite3_exec(db, CMD_CREATE_DP_INDEX, NULL, NULL, &err_msg) != SQLITE_OK) { syslog(LOG_ERR, "Create data_planner index fail: %s", err_msg); goto out; } ret = 0; out: if (err_msg) sqlite3_free(err_msg); if (db) sqlite3_close(db); return ret;
  • 7. Create DB/table/index ● Check if using index ● “EXPLAIN <your query>” ○ ex: EXPLAIN SELECT * FROM a WERHE name = “1”; ○ Will show IdxRowid/IdxGE if apply index
  • 8. Create DB/table/index sqlite> explain select * from users where name='foo'; 0|Trace|0|0|0||00| 1|String8|0|1|0|foo|00| 2|Goto|0|18|0||00| 3|OpenRead|0|2|0|2|00| 4|OpenRead|1|3|0|keyinfo(1,BINARY)|00| 5|IsNull|1|15|0||00| 6|Affinity|1|1|0|bb|00| 7|SeekGe|1|15|1|1|00| 8|IdxGE|1|15|1|1|01| 9|IdxRowid|1|2|0||00| ...blahblah 21|Goto|0|3|0||00|
  • 9. Create DB/table/index ● When to create? ○ System startup ○ Program startup ○ In every query
  • 10. Prepare SQL sqlite3 *db = NULL; sqlite3_stmt *stmt = NULL; int ret = DP_ERROR; if (sqlite3_open(DATA_PLANNER_DB_PATH, &db) != SQLITE_OK) { syslog(LOG_ERR, "Open sqlite fail: %s", DATA_PLANNER_DB_PATH); goto out; } char *sql = "SELECT sum(tx_bytes) as total_tx_bytes,sum(rx_bytes) as total_rx_bytes FROM data_planner WHERE datetime(timestamp, 'localtime') >= ? AND datetime(timestamp, 'localtime') < ?;"; if (sqlite3_prepare_v2(db, sql, strlen(sql), &stmt, NULL) != SQLITE_OK) { syslog(LOG_ERR, "SQL prepare fail: %s", sql); goto out; }
  • 11. SQL Bind sqlite3_bind_text(stmt, 1, begin_date, -1, NULL); sqlite3_bind_text(stmt, 2, end_date, -1, NULL); // Also, there is no uint64, only int64
  • 12. SQL Query if (sqlite3_step(stmt) == SQLITE_ROW) { *total_tx_bytes = sqlite3_column_int64(stmt, 0); *total_rx_bytes = sqlite3_column_int64(stmt, 1); } else { syslog(LOG_ERR, "SQL fail: Error when get previous total data: %s", sqlite3_errmsg(db)); goto out; } ret = 0; out: if (stmt) sqlite3_finalize(stmt); if (db) sqlite3_close(db); return ret;
  • 13. SQL Query ● sqlite3_exec ○ sqlite3_prepare_v2 + sqlite3_step + sqlite3_finalize ○ Good for insertion/create table/transaction ○ Bad for query
  • 14. SQL Query sqlite3_exec( sqlite3*, const char *sql, int (*callback)(void*, int column_num, char**, char**), void *, char **errmsg } // void * is for user data
  • 15. Timezone issue ● Use UTC ● In C ○ Use gmtime_r instead of localtime_r ● In SQLite3 ○ Insert using datetime(?, 'unixepoch') ■ ? is time_t ○ Query using datetime(timestamp, 'localtime')
  • 16. SQL Debug void* sqlite3_trace( sqlite3* db, trace_callback, void* udp); // Register sql callback and call it every time before executing void trace_callback( void* udp, const char* sql ); // udp means user data pointer
  • 17. SQLite Busy Handle ● SQlite may be locked sometimes, solution: ○ sqlite3_busy_handle ■ More flexible, can add sleep() and retry times ○ sqlite3_busy_timeout ○ http://www.bubuko.com/infodetail-240892.html ○ http://www.360doc. com/content/10/1214/12/87000_77984300.shtml
  • 18. Relational Database ● MariaDB/MySQL/Percona ○ Multiple engines ■ MyISAM ● Table lock ■ InnoDB ● Row lock ● Transaction ● PostgreSQL ● SQLite
  • 19. Relational Database ● Replication ○ For read ○ Master/Slave ● Sharding ○ For read/write ○ Do not rely on auto sharding