Created
October 25, 2017 06:59
-
-
Save yizhang82/e0cf283340860710cdc7ed54131d200a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
var sqlite = require('sqlite3').verbose(); | |
var db = new sqlite.Database('test_db'); | |
function vote(voter, callback) { | |
var val; | |
var getStmt = `SELECT Name, Count FROM Voters WHERE Name="${voter}"`; | |
console.log(getStmt); | |
db.get(getStmt, function(err, row) { | |
if (!row) { | |
console.log("VOTER NOT FOUND"); | |
var insertSql = `INSERT INTO Voters (Name, Count) VALUES ("${voter}", 1)`; | |
console.log(insertSql); | |
db.run(insertSql, function (err) { | |
val = 1; | |
callback(err, val); | |
}); | |
} | |
else { | |
val = row["Count"]; | |
console.log(`COUNT = ${val}`); | |
val += 1; | |
// update | |
var updateSql = `UPDATE Voters SET Count = ${val} WHERE Name = "${voter}"`; | |
console.log(updateSql); | |
db.run(updateSql, function (err) { | |
callback(err, val); | |
}); | |
} | |
}); | |
} | |
console.log('sqlite3...'); | |
var stmt = "CREATE TABLE IF NOT EXISTS Voters (Name TEXT, Count int)"; | |
console.log(stmt); | |
db.run(stmt, function (err) { | |
if (err) { | |
console.log(JSON.stringify(err)); | |
return; | |
} | |
vote("john doe", function (err, val) { | |
if (err) { | |
console.log(JSON.stringify(err)); | |
return; | |
} | |
console.log(`New vote for John Doe is ${val}`); | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment