Connect To SQLite DB using CFML via CommandBox Task Runners
Here's a quick trick on working with a SQLite DB from CFML quicky and easily. I was playing with the SQLite DB that the original .NET version of GitHub for Desktop and I wanted to access the db file from the CLI to query data and manipulate it. The steps where very easy.
Create a Blank Task Runner
The very first step was the easiest, and this was to create a blank CommandBox Task Runner:
task create --open
Download the SQLite JDBC jar
I grabbed the latest JDBC driver for SQLite from this URL and I placed sqlite-jdbc-3.23.1.jar in a /lib folder. This line of code at the top of my task runner will classload the jar from the lib folder relative to the working directory of my task..
classLoad( filesystemUtil.resolvepath( 'lib' ) );
Declare the Connection Details
Next I created a struct that represents the connection details for the SQLite connection.Thanks to an old post of Ray Camden's to get the correct class name and JDBC URL.
var myDSN = { class: 'org.sqlite.JDBC', connectionString: 'jdbc:sqlite:#filesystemUtil.resolvepath( '~/AppData/Local/GitHub/cache.db' )#' };
Note that tilde (~) works in CommandBox even on Windows to reference your user home dir.
Run The SQL
And finally I ran my query against the SQLite DB using a normal CFQuery tag. You can use queryExecute() if you like. I found this version easier to read since there are no parameters.
query name='local.qry' datasource=myDSN { echo( " SELECT key, typename FROM main.CacheElement WHERE key = 'tracked-repositories' " ) }
Notice, I'm using Lucee's nice feature of supplying a struct for the datasource details instead of a string.This prevents me from needing to create the datasource. More info here.
Finished Product
Here is the entire Task Runner in one piece including a line to output the query result to the console.
component { function run() { // https://github.com/xerial/sqlite-jdbc/releases classLoad( filesystemUtil.resolvepath( 'lib' ) ); var myDSN = { class: 'org.sqlite.JDBC', connectionString: 'jdbc:sqlite:#filesystemUtil.resolvepath( '~/AppData/Local/GitHub/cache.db' )#' }; query name='local.qry' datasource=myDSN { echo( " SELECT key, typename FROM main.CacheElement WHERE key = 'tracked-repositories' " ) } print.line( formatterUtil.formatJSON( qry ) ); } }
I hope this sparks some ideas in your head. Play around and see just how powerful CFML can be from the CLI, especially when we have all of the Java libraries out there at our disposal.