According to the snippet above, node.js server act as a client to the HANA server with announce “client” object and call connect function, we will modify the code to run SQL after connected successfully.
First is CREATE TABLE statement:
Let’s expand the callback function, we can know that the callback function do the following tasks:
- Print out error info if error occurs and return.
- Print out client state.
- Run create table SQL.
You may have recognized that there is another callback function in the “client.exec()” statement, that true, and it defines what to do after the SQL runs on database, I think you have understand the basic concept of callback function, please note that callback functions may be nested, which may lead to “callback hell” if too much, we will see how to solve it later.
Run the applications will get the result as follow:
And let’s check whether this table is created in HANA:
Please note that the column name will be upper cased automatically.
Someone may argue that is that possible to write code like this:
I have to say yes–according to the test–but not recommended, this is totally blocking style code which is same as Java. The reason is that you cannot make sure that the order of function execution, as we said that node.js is non-blocking, this case happen to work just because connect() is a blocking function, you can try it by disconnect the network and run this program, it trying to connect until timeout, but remember not all functions are so blocking-friendly, actually most of functions in node.js is non-blocking.
Next let’s try INSERT statement:
The only difference is the parameter of callback function, a variable “affectedRows” to return the rows inserted successfully. And this operation also add a destroy function, the implementation is as follow:
Do remember to close the connection when terminate the program.
Let’s try query after insert:
Note that the callback parameter changed again, rows is the result set of this query, we can conclude the definition of callback function depends on the SQL statement, the output should be:
Finally is the UPDATE operation:
The parameter of callback function is the same as INSERT.
And finally the DELETE operation:
These is the basic SQL statement, we will see more complex cases in the next part.