How to use sqlite3 - 10 common examples

To help you get started, we’ve selected a few sqlite3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nebrius / contact-scheduler / dist / main / db.js View on Github external
function init(cb) {
    var isNewDB = !fs_1.existsSync(dbPath);
    var sqlite3 = sqlite3_1.verbose();
    util_1.log("Loading database from " + dbPath);
    async_1.waterfall([
        function (next) { return (db = new sqlite3.Database(dbPath, next)); },
        function (next) {
            if (!isNewDB) {
                next(undefined);
                return;
            }
            util_1.log("New database detected, initializing");
            // Need to slice off extra params so can't pass cb or next directly here
            async_1.series([
                function (nextInit) { return db.run(CALENDAR_SCHEMA, function (err) { return nextInit(err); }); },
                function (nextInit) { return db.run(CONTACT_SCHEMA, function (err) { return nextInit(err); }); },
                function (nextInit) { return db.run(SCHEDULE_SCHEMA, function (err) { return nextInit(err); }); },
                function (nextInit) { return db.run("INSERT INTO " + SCHEDULE_TABLE_NAME + "(queue, lastUpdated) VALUES(?, 0)", ['[]'], function (err) { return nextInit(err); }); }
            ], function (err) { return next(err); });
github tsycnh / WeChatExporter / development / js / controller / chatDetail.js View on Github external
$scope.outputPath.rootFolder = $stateParams.outputPath;
        $scope.outputPath.sqliteFile = path.join($scope.outputPath.rootFolder,"data.sqlite");
        $scope.outputPath.audioFolder = path.join($scope.outputPath.rootFolder,"audio");
        $scope.outputPath.imageFolder = path.join($scope.outputPath.rootFolder,"image");
        $scope.outputPath.imageThumbnailFolder = path.join($scope.outputPath.rootFolder,"image","thumbnail");
        $scope.outputPath.videoFolder = path.join($scope.outputPath.rootFolder,"video");
        $scope.outputPath.videoThumbnailFolder = path.join($scope.outputPath.rootFolder,"video","thumbnail");
        $scope.outputPath.resourceFolder = path.join($scope.outputPath.rootFolder,"resource");

        $scope.meInfo['headPath'] = path.join('file://',$scope.outputPath.resourceFolder,'me.png')
        $scope.otherInfo['headPath'] = path.join('file://',$scope.outputPath.resourceFolder,'other.png')

        console.log($scope.outputPath);

        //- 打开sqlite数据库
        $scope.db = new sqlite3.Database($scope.outputPath.sqliteFile,sqlite3.OPEN_READONLY,function (error) {
            if (error){console.log("Database error:",error);}
        });
        //- 计算一共有多少页
        var sqlite = require('sqlite-sync'); //requiring
        sqlite.connect($scope.outputPath.sqliteFile);
        $scope.totalMessageCount = sqlite.run("SELECT count(*) as count from ChatData")[0].count;
        $scope.totalPageCount = Math.ceil($scope.totalMessageCount/$scope.limitGap);

        $scope.currentPage = 1;
        //- 按照limit规则,每按一次loadMore载入指定数量的消息
        //$scope.loadMore();// 载入数据库内容
        if($scope.generateHtml == "true")
        {
            fse.emptyDirSync("../distHtml");
        }
        $scope.goToPage($scope.currentPage);
github talltom / PiThermServer / server.js View on Github external
*/

// Load node modules
var fs = require('fs');
var sys = require('sys');
var http = require('http');
var sqlite3 = require('sqlite3');

// Use node-static module to server chart for client-side dynamic graph
var nodestatic = require('node-static');

// Setup static server for current directory
var staticServer = new nodestatic.Server(".");

// Setup database connection for logging
var db = new sqlite3.Database('./piTemps.db');

// Write a single temperature record in JSON format to database table.
function insertTemp(data){
   // data is a javascript object   
   var statement = db.prepare("INSERT INTO temperature_records VALUES (?, ?)");
   // Insert values into prepared statement
   statement.run(data.temperature_record[0].unix_time, data.temperature_record[0].celsius);
   // Execute the statement
   statement.finalize();
}

// Read current temperature from sensor
function readTemp(callback){
   fs.readFile('/sys/bus/w1/devices/28-00000400a88a/w1_slave', function(err, buffer)
	{
      if (err){
github graulund / pyramid / server / db.js View on Github external
createDatabaseFromEmpty((err) => {
		if (err) {
			throw err;
		}
		else {
			// Open database
			var db = new sqlite.Database(DB_FILENAME);
			initializeDb(db);
			mainMethods(main, db);

			if (typeof callback === "function") {
				callback();
			}
		}
	});
};
github darrellenns / n1mm-display / app.js View on Github external
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


//---------------------------------database helpers
var sqlite3=require('sqlite3').verbose();
var db=new sqlite3.Database(settings.n1mm_db);
var contestNR=-2;

var dxlog=function(clause,callback,complete){
	db.each("SELECT strftime('%s',TS) as t,* from DXLOG WHERE ContestNR="+contestNR.toString()+" "+clause,function(err,row){
		if(err) throw(err);
		row['id']=row.t+row.Call+row.Band.toString()+row.Mode;
		callback(row);
	},complete);
}

var dxlog_addinfo=function(row,callback){
	geo.resolve(row,function(geodata){
		row['coord']=geodata;
		row.t=parseInt(row.t);
		callback(row);
github nlaz / monkbot / monkbot.js View on Github external
/**
 *     _____         _   _____     _   
 *    |     |___ ___| |_| __  |___| |_ 
 *    | | | | . |   | '_| __ -| . |  _|
 *    |_|_|_|___|_|_|_,_|_____|___|_|  
 *
 *  Your Slack servant for daily committing
 */
 
require('dotenv').config();

var jsdom         = require("jsdom");
var request       = require("request");
var dateFormat    = require('dateformat');
var CronJob       = require('cron').CronJob;
var sqlite3       = require('sqlite3').verbose();
var RtmClient     = require('@slack/client').RtmClient;
var WebClient     = require('@slack/client').WebClient;
var RTM_EVENTS    = require('@slack/client').RTM_EVENTS;
var CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;

var convos = {};
var db;

var DEBUG_LEVEL = 'info'; // 'debug', 'info', 'verbose'

var token = process.env.SLACK_API_TOKEN || '';

var usage = "*MonkBot* - Your courteous Slack reminder to commit daily\n" +
            "`@monkbot help` - Displays list of commands monkbot recognizes.\n" +
            "`@monkbot users` - Displays list of all users.\n" +
            "`@monkbot report` - Report daily commiters.\n" +
github taichi / rx-sqlite / src / index.js View on Github external
// @flow
import * as sqlite from "sqlite3";
import db from "./database";
import stmt from "./statement";

/**
 * see {@link https://github.com/mapbox/node-sqlite3/wiki/Debugging|node-sqlite3/Debugging}
 */
export function verbose() {
  sqlite.verbose();
}

/**
 * The database is opened in read-only mode.
 */
export const OPEN_READONLY = sqlite.OPEN_READONLY;

/**
 * The database is opened for reading and writing if possible.
 */
export const OPEN_READWRITE = sqlite.OPEN_READWRITE;

/**
 * The database is opened for reading and writing, and is created if it does not already exist.
 */
export const OPEN_CREATE = sqlite.OPEN_CREATE;

/**
 * supported database opening flags
 */
export type Mode = OPEN_READONLY | OPEN_READWRITE | OPEN_CREATE;
github AnalyticalGraphicsInc / 3d-tiles-tools / tools / lib / tilesetToDatabase.js View on Github external
.then(function () {
            // Create the database.
            db = new sqlite3.Database(outputFile, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE);
            dbRun = Promise.promisify(db.run, {context: db});

            // Disable journaling and create the table.
            return dbRun('PRAGMA journal_mode=off;');
        })
        .then(function () {
github tramseyer / cell-geolocation / cell-geolocation.js View on Github external
const http = require('http');
const sqlite3 = require('sqlite3');
const path = require('path');
const Url = require('url');
const util = require('util');
const fs = require('fs');
const request = require(path.join(__dirname, 'request.js'));
const mlsDb = new sqlite3.Database(path.join(__dirname, 'mls_cells.sqlite'), sqlite3.OPEN_READONLY);
const ociDb = new sqlite3.Database(path.join(__dirname, 'oci_cells.sqlite'), sqlite3.OPEN_READONLY);
const glmDb = new sqlite3.Database(path.join(__dirname, 'glm_cells.sqlite'), sqlite3.OPEN_READWRITE);
const uwlDb = new sqlite3.Database(path.join(__dirname, 'uwl_cells.sqlite'), sqlite3.OPEN_READWRITE);
const ownDb = new sqlite3.Database(path.join(__dirname, 'own_cells.sqlite'), sqlite3.OPEN_READWRITE);

const approximatedRange = 2147483648;

const defaultLatitude = 46.909009;
const defaultLongitude = 7.360584;
const defaultRange = 4294967295;

const mlsDbMtime = new Date(fs.statSync(path.join(__dirname, 'mls_cells.sqlite')).mtime).getTime()/1000|0;
console.log('Main database (Mozilla) last modifed at:', mlsDbMtime);

const OPENCELLID_API_KEY = process.env.OPENCELLID_API_KEY;
if (typeof OPENCELLID_API_KEY != 'undefined') {
  console.log('Using OpenCellId API key:', OPENCELLID_API_KEY);
} else {
  console.warn('No OpenCellId API key supplied via: OPENCELLID_API_KEY');
}
github transistorsoft / background-geolocation-console / src / server / database / migrate.js View on Github external
/**
* Migrate records created from before Sequalize was introduced
*/

var path = require('path');
var sqlite3 = require('sqlite3').verbose();
var fs = require('fs');

var DB_FILE = path.resolve(__dirname, 'background-geolocation.db');
var LocationModel = require('./LocationModel.js');

var dbh;

if (!fs.existsSync(DB_FILE)) {
  console.log('- Failed to find background-geolocation.db: ', DB_FILE);
} else {
  dbh = new sqlite3.Database(DB_FILE);
  var query = 'SELECT * FROM locations';

  var onQuery = function (err, rows) {
    if (err) {
      console.log('ERROR: ', err);

sqlite3

Asynchronous, non-blocking SQLite3 bindings

BSD-3-Clause
Latest version published 12 months ago

Package Health Score

81 / 100
Full package analysis