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 .

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 大莽阅读 2,372评论 0 0
  • “长老,B3429是否可以评为低等生物星球?” “恩,差不多可以了,毕竟用他们的时间计算,那首诗已经过去那么久了,...
    彭杨森阅读 4,200评论 2 1
  • 混编的时候导入的pod文件 因为用swift的必须用use_frameworks!会把静态库编译成framewor...
    开心一刻_阅读 2,187评论 0 0
  • 也许是真的停得太久了吧。 最近和朋友在一起聊天的时候,总有“时间过得真快,几年前如何如何”之类的感叹,感觉除了年龄...
    manbanpaiing阅读 1,666评论 2 2
  • 1 啊可以大家一起养鱼 出去卖 2 大家一去去卖草药 3 创业卖苞米 1.创办农家乐的相关程序 各个地方创办农家乐...
    精神分裂_5d2b阅读 2,463评论 0 0

友情链接更多精彩内容