Search code examples
coldfusion

ColdFusion: Trying to query database in CFScript


My boss wants me to use cfscript instead of tags for database interaction. Does anybody know of any good tutorials? I bought the Adobe ColdFusion application development book, vol 2. But it does not have much on scripting. I did google and found this site, but it did not explain much.

Does any body know of any good tutorials on accessing the data base in CFScript?

Basically I have to convert the following to using CFScript:

<cfquery name="drafts" datasource="ICEchat">
    SELECT * from Messages where IsTemp=1 and LinkA=#FORM.LinkA# and LinkB=#FORM.LinkA#
</cfquery>
<cfif drafts.recordcount GT '0'>
    <cfquery name="Attachments" datasource="ICEchat">
        SELECT * FROM Attachments where id=2
    </cfquery>
    { Message:"<cfoutput query="drafts">#Message#</cfoutput>", Attachments:[<cfoutput query="attachments">
        "#url#"<cfif attachments.currentRow LT attachments.recordcount>,</cfif>
    </cfoutput>]}
<cfelse>
    <cfquery name="addrecord" datasource="ICEchat">
        INSERT INTO Messages 
        VALUES(1,1,' ',1)
    </cfquery>
    { Message:"NA", Attachments:[]}
</cfif>

Solution

  • From the 4th link on google for "cfscript query tutorial":

    <CFSCRIPT>
        myQry = new Query(); // new query object     
        myQry.setSQL("select bookid, title, genre from app.books where bookid = :bookid"); //set query
        myQry.addParam(name="bookid",value="5",CFSQLTYPE="CF_SQL_INTEGER"); // add query param
        qryRes = myQry.execute(); // execute query
        writedump(qryRes.getResult().recordcount, true); // get resultcount
        writedump(qryRes.getResult(), false); // dump result
        writeoutput('<BR>');
    </CFSCRIPT>
    

    That ought to tell you everything you need to know.

    Also, you really should not be creating JSON manually, no matter how simple it is. Use serializeJson().