{"id":647,"date":"2014-12-23T12:09:41","date_gmt":"2014-12-23T12:09:41","guid":{"rendered":"http:\/\/smartfoxserver.com\/blog\/?p=647"},"modified":"2017-04-18T10:53:23","modified_gmt":"2017-04-18T10:53:23","slug":"querying-the-database-and-sending-resultsets","status":"publish","type":"post","link":"https:\/\/smartfoxserver.com\/blog\/querying-the-database-and-sending-resultsets\/","title":{"rendered":"Querying the database and sending resultsets"},"content":{"rendered":"<p>This recipe shows how to read data from a database and send it to the client in a convenient format.<!--more--><\/p>\n<div class=\"dottedYellowBox\">We use MySQL for this recipe, but you can easily use any other database of your choice (read <a title=\"How to setup a connection to an external Database\" href=\"http:\/\/smartfoxserver.com\/blog\/how-to-setup-a-connection-to-an-external-database\/\">this tutorial<\/a>). We use standard SQL in all code so it can be ported to any other RDBMS.<\/div>\n<p>The <strong>SFSDBManager.executeQuery<\/strong> method on the server-side provides an effective way to execute a SQL query and obtain an SFSArray-based data strcuture which can be sent to the client on the fly.<br \/>\nFor more details on this we recommend to consult the <a href=\"http:\/\/docs2x.smartfoxserver.com\/api-docs\/javadoc\/server\/com\/smartfoxserver\/v2\/db\/SFSDBManager.html#executeQuery(java.lang.String)\" target=\"_blank\">SFSDBManager javadoc<\/a>.<\/p>\n<p>In this simple example we are going to obtain a list of records from a people database and send them over to the client in a few lines of code.<\/p>\n<p>The source files (the download link is provided at the end of this recipe) come with a MySQL dump that can be used to generate the database table used by the Extension. These are the steps to setup and test the example application.<\/p>\n<ul>\n<li>We need a database called <strong>sfs2x<\/strong>, if you don&#8217;t have one please create it.<\/li>\n<li>Use the provided <em>people-table.sql<\/em> file to import the &#8216;people&#8217; table into the database.<\/li>\n<li>Deploy the extension by copying it in a subfolder of <strong>{sfs-install-dir}\/SFS2X\/extensions\/<\/strong>. You can choose any name for the subfolder, for example <strong>peopleExt<\/strong>.<\/li>\n<li>Launch the AdminTool, choose the <a href=\"http:\/\/docs2x.smartfoxserver.com\/GettingStarted\/admintool-ZoneConfigurator\" target=\"_blank\">Zone Configurator<\/a> module and edit the <em>BasicExamples<\/em> zone. Set the Extension for the Zone as follows:\n<ul>\n<li><em>Name<\/em>: peopleExt (or the name you have chosen, if different)<\/li>\n<li><em>Type<\/em>: JAVA<\/li>\n<li><em>Main class<\/em>: sfs2x.extension.test.people.PeopleExtension<\/li>\n<\/ul>\n<\/li>\n<li>In the <em>General<\/em> tab of the Zone Configurator make sure that the<strong> custom login<\/strong>is turned off.<\/li>\n<li>At this point you should be ready to restart SFS2X, unless you also need to setup the database connection.\u00a0If you haven&#8217;t done this previously we suggest to <a title=\"How to setup a connection to an external Database\" href=\"http:\/\/smartfoxserver.com\/blog\/how-to-setup-a-connection-to-an-external-database\/\">follow this other recipe<\/a>.<\/li>\n<\/ul>\n<p>You can now startup the provided client and test the Extension.<\/p>\n<h3><strong>\u00bb The request handler<\/strong><\/h3>\n<p>In the source code you will find a <strong>GetPeopleHandler<\/strong> class which responds to the &#8220;getPeople&#8221; request coming from the client. Let&#8217;s take a look at what it does:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class GetPeopleHandler extends BaseClientRequestHandler\r\n{\r\n    @Override\r\n    public void handleClientRequest(User sender, ISFSObject params)\r\n    {\r\n        IDBManager dbManager = getParentExtension().getParentZone().getDBManager();\r\n        String sql = &quot;SELECT * FROM people&quot;;\r\n         \r\n        try\r\n        {\r\n            \/\/ Obtain a resultset\r\n            ISFSArray res = dbManager.executeQuery(sql, new Object[] {});\r\n             \r\n            \/\/ Populate the response parameters\r\n            ISFSObject response = new SFSObject();\r\n            response.putSFSArray(&quot;people&quot;, res);\r\n             \r\n            \/\/ Send back to requester\r\n            send(&quot;getPeople&quot;, response, sender);\r\n        }\r\n        catch (SQLException e)\r\n        {\r\n            trace(ExtensionLogLevel.WARN, &quot;SQL Failed: &quot; + e.toString());\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p>The returned SFSArray contains all the records represented as SFSObject(s), which makes it very easy to extract the field values. This is how it is done on the client side (ActionScript 3) when the <strong>EXTENSION_RESPONSE<\/strong> event is handled:<\/p>\n<pre class=\"brush: as3; title: ; notranslate\" title=\"\">\r\nprivate function onExtensionResponse(evt:SFSEvent):void\r\n{\r\n    var params:ISFSObject = evt.params.params as ISFSObject\r\n    var peopleArray:ISFSArray = params.getSFSArray(&quot;people&quot;)\r\n     \r\n    var dump:String = &quot;PEOPLE LIST RECEIVED:\\n\\n&quot;\r\n     \r\n    for (var i:int = 0; i &lt; peopleArray.size(); i++)\r\n    {\r\n        var item:ISFSObject = peopleArray.getSFSObject(i)\r\n        dump += &quot;    &gt; &quot; + item.getUtfString(&quot;name&quot;) + &quot;, &quot; + item.getUtfString(&quot;location&quot;) + &quot;, &quot; + item.getUtfString(&quot;occupation&quot;) + &quot;\\n&quot;\r\n    }\r\n     \r\n    dTrace(dump)\r\n    dTrace(&quot;Total records: &quot; + peopleArray.size())\r\n}\r\n<\/pre>\n<p>All we need to do is loop through each element in the received SFSArray. Each item is an SFSObject that represents one row of the resultset which allows us to access its fields by name. In our case the field names are: <em>name<\/em>, <em>location<\/em>, <em>occupation<\/em>.<\/p>\n<div class=\"dottedYellowBox\" style=\"text-align: center;\"><strong><a href=\"http:\/\/smartfoxserver.com\/download\/get\/215\">DOWNLOAD the source files for this recipe<\/a><\/strong><\/div>\n","protected":false},"excerpt":{"rendered":"<p>This recipe shows how to read data from a database and send it to the client in a convenient format.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[5],"tags":[21,31,7],"_links":{"self":[{"href":"https:\/\/smartfoxserver.com\/blog\/wp-json\/wp\/v2\/posts\/647"}],"collection":[{"href":"https:\/\/smartfoxserver.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smartfoxserver.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smartfoxserver.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smartfoxserver.com\/blog\/wp-json\/wp\/v2\/comments?post=647"}],"version-history":[{"count":1,"href":"https:\/\/smartfoxserver.com\/blog\/wp-json\/wp\/v2\/posts\/647\/revisions"}],"predecessor-version":[{"id":648,"href":"https:\/\/smartfoxserver.com\/blog\/wp-json\/wp\/v2\/posts\/647\/revisions\/648"}],"wp:attachment":[{"href":"https:\/\/smartfoxserver.com\/blog\/wp-json\/wp\/v2\/media?parent=647"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smartfoxserver.com\/blog\/wp-json\/wp\/v2\/categories?post=647"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smartfoxserver.com\/blog\/wp-json\/wp\/v2\/tags?post=647"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}