Guest User

Untitled

a guest
Dec 21st, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. //assuming i have database:
  2. Person_table(ID int A_I, NAME varchar, AGE int)
  3. //code:
  4. var p = new Person("John", 22);
  5. p.writeToDatabase();
  6. //the object is now written in database
  7.  
  8. var mysql = require('mysql');
  9. var conn = mysql.createPool({
  10. host : 'localhost',
  11. database: 'db_name',
  12. user: 'user_name',
  13. password : 'pass',
  14. multipleStatement: true,
  15. connectionLimit : 10
  16. });
  17.  
  18. conn.getConnection(function(err){
  19. if(err) throw err;
  20. });
  21.  
  22. module.exports = conn;
  23.  
  24. var db = require('./db.js');
  25.  
  26. function Person(n, a) {
  27. this.name = n;
  28. this.age = a;
  29. }
  30.  
  31. Person.prototype.writeToDatabase = function (callback) {
  32. db.query("INSERT INTO Person_table(NAME, AGE) VALUES(?,?)", [this.name, this.age], function (err, rows) {
  33. if (err) return callback(err);
  34. else return callback(null, rows);
  35. });
  36. }
  37.  
  38. module.exports = Person;
  39.  
  40. var Person = require('./person.js')
  41.  
  42. var p = new Person("John", 22);
  43.  
  44. p.writeToDatabase(function(err, rows){
  45. if(err) console.log(err);
  46. else console.log("written to DB");
  47. });
Add Comment
Please, Sign In to add comment