Sqlite3 && orm node.js && $.get ()

  To connect the server and the client, we should know what information to get or to send in server and client. 

1. Server

  I started a server by ‘express’, a dependency of node. And I’ll use dependency ‘orm’ to connect with sqlite profile to get the statics in it. Sqlite is a software to help us create and manage databases. Also, we have to create a dependency.

(1)create and manage databases and tables in sqlite3

  Open the terminal ,and input ‘sqlite3’ to open sqlite. If you want to create a ‘.db’ profile , you can input ‘sqlite3 [ database name of yours ].db’,like:

$ sqlite3 mydatabase.db

This will help you create a database in the current folder. To create a new table in the database you can :

sqlite> create table [ your table’s name] (

     …> [ row name ]  [ data type ]([ the length])  [ if null ] ) ;

‘;’ can help u to back to ‘sqlite >’.It’s an example to create a table :

sqlite> create table students (

     …> id int primary key not null,

     …>name char not null);

  To see all the tables you can:

sqlite> .table

And it’s easy to delete a table:

sqlite> drop table [ your table’s name ]

  After we create database and tables, we can use sqlite to insert data into it, but we can use ‘orm’ to create tables or insert data as well. To insert data in sqlite ,for example:

sqlite> insert table students ( id, name)

     …> values 1, Tom ;

(2)use orm to manage databases in node.js && create API

  Before we use orm , we should ‘require’ it into our js profile . And then we are able to connect with our database in our project.

let orm = require(“orm”);

orm.connect(‘sqlite:/[ GetFullPath of your database ]’,function(err, db) {

    if(err)returnconsole.error(‘Connection error: ‘+ err);

    elseconsole.log(‘success!’);

});

If you use express and orm at the same time , you can use this to connect with database in sqlite3 : ( this is in wiki of node-orm2)

app.use(orm.express(“sqlite://username:password@host/database”, {

define: function (db, models, next) {

models.person = db.define(“person”, { … });

next();

}

}));

app.listen(80);

app.get(“/”, function (req, res) {

// req.models is a reference to models used above in define()

req.models.person.find(…);

});

As I use ‘express’ to start my server , so I connect orm and use orm in this way. Now we can easily get requests , find what we need in our databases , and send the response to client.

This is my example to connect with sqlite by orm models:

app.use(orm.express(‘[ GetFullPath of your database ]’,{

    define:function(db, models, next) {

// ‘db’ is your database profile , ‘models’  is a map to your database , it can help you to get data in your database to your js profile.’Next’ is what you’ll do next.

models.students = db.define(“students”, {

id:Number,

name:String

});

next();

}

}));

And then we can create an API which can help to find data of students in our database.

app.get(‘/student’,function(req,res) {

   req.models.students.find({id:1},function(err,student) {

   console.log(student);

   res.send(student);

   })

});

There are other methods of orm models to manage the database ( when we use ‘express’ as well ) :

req.models.students.create( { … },function (err, …) { … };

//to create data in table ‘students’

And following is an example to change data of one student in table:

req.models.students.find({id:id},function(err,student){

    if(req.body.crtname!==””&&id!==”){

        student[0].name=req.body.crtname;

//To use ‘body’  u need dependency ‘body-parser’

        student[0].save(function(err) {

            if(err) {

            console.log(‘err’+ err);

            }else{

            res.send(student)

            }

       });

}else{

res.status(400).send(‘ please input in correct way ‘)

}

});

Now we can get the request and send our data . Next I’ll share how to show our data to client by jquery.

2.Client

For example , if you want to add your student (id:1) information to the table of your website , you can set an ‘id’ to your button’s tag , and use API we wrote to get data after the tag of this ‘id’ has been clicked.

$(document).ready ( function () {

$( ‘#submit’ ).click (  function () {

  $( ‘#tablebody’ ).empty();

//clear what there was in the table before clicked

      $.get(‘/student’,function(ans) {

      let student = ans;

 //’ans’ is what returns by ‘/student’, and it’s an array of the student’s information of ‘id:1’.

//the array is: [ { id:1 , name : Tom } ] ,as we input to our database.

      let str = ` <tr> <td> student[0].id </td>

                            <td> student [0].name </td> </tr>`;

      $( ‘#tablebody’ ).append( str );

     });

}  )

} )

‘$.get()’ can help us get what entering the API will returns .  After we get data we can ‘apend’ our data into our website. And the client will get the data in the website .

    原文作者:Irrevocability
    原文地址: https://www.jianshu.com/p/f8dcadbce9ab
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞