How it works…

Running tryDbAccess() isn't hard to figure out: the constant query goes to the server, and an array with a single row comes back. The output of our code would have been as follows:

Year was 1960

The second query gets more interesting. Apart from the details of actually writing the SQL query (which is beyond the objectives of this book) the interesting point is the returned array, each with an object with the selected fields:

IN India 1301
BR Brazil 1203
RU Russian Federation 1090
DE Germany 1061
CN China 810
FR France 633
ES Spain 616
JP Japan 605
IT Italy 575
MX Mexico 556

Now, let's get to the last example. We are seeing several ways of creating the statement that will be executed.

The INSERT uses a prepared statement. A good way to prepare safe queries (meaning, they cannot be involved in SQL injection hacks) is by using prepared strings. The .prepare() method is interesting: given a string, it returns a function, that when called with the actual parameters to use, will itself return the string to use in the query. Of course, you can also build the function by hand, as I did in the other examples—but then it's up to you to make sure that the resulting query is safe! 

The .escape() method can help building a safe query string, if you don't want to use .prepare(). See more at https://github.com/mscdex/node-mariasql.

The subsequent SELECT uses a string created by hand (nothing too original here) but the UPDATE shows another style: using ? symbols as placeholders. In that case, you must also provide an array of values that will replace the placeholders; it's fundamental that the order of the values in the array matches the expected arguments. 

Next, the second SELECT also uses placeholders, but adds a tweak: passing an object with the useArray:true option, the function performs a tad faster, because it doesn't create objects for each row, and simply returns arrays. This has a problem, however, because now you have to remember what each position of the array means. 

The results of the code are as expected: first a single line, showing that a country was actually created, with the values we passed; then, the same record but with a changed name, and finally a zero showing that the country doesn't exist any more:

1 '42' 'DOUGLASADAMSLAND'
1 '42' 'NEW NAME'
0
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.86.183