Boxlang 1.x Stable Released
BoxLang : A Modern Dynamic JVM Language
LogoLogo
APIDocsDownloadTrySourceSupport
  • Introduction
    • Contributing Guide
    • Release History
      • 1.1.0
      • 1.0.1
      • 1.0.0
      • RC Stage
        • 1.0.0-RC.1
        • 1.0.0-RC.2
        • 1.0.0-RC.3
      • Beta Stage
        • 1.0.0-Beta27
        • 1.0.0-Beta26
        • 1.0.0-Beta25
        • 1.0.0-Beta24
        • 1.0.0-Beta23
        • 1.0.0-Beta22
        • 1.0.0-Beta21
        • 1.0.0-Beta20
        • 1.0.0-Beta19
        • 1.0.0-Beta18
        • 1.0.0-Beta17
        • 1.0.0-Beta16
        • 1.0.0-Beta15
        • 1.0.0-Beta14
        • 1.0.0-Beta13
        • 1.0.0-Beta12
        • 1.0.0-Beta11
        • 1.0.0-Beta10
        • 1.0.0-Beta9
        • 1.0.0-Beta8
        • 1.0.0-Beta7
        • 1.0.0-Beta6
        • 1.0.0-Beta5
        • 1.0.0-Beta 4
        • 1.0.0-Beta3
        • 1.0.0-Beta2
    • About This Book
      • Authors
  • Getting Started
    • Overview
      • Multi-Runtime
      • Instructions & Interpreters
      • CommandBox CLI
      • Quick Syntax Guide
        • Differences From CFML
      • Frequently Asked Questions
      • Running ColdFusion/CFML Apps
        • Migrating from Adobe ColdFusion
        • Migrating From Lucee CFML
    • Installation
      • Modules
    • Running BoxLang
      • AWS Lambda
      • CommandBox
      • Chromebooks
      • CLI Scripting
      • Docker
      • JSR-223 Scripting
      • MiniServer
      • Try BoxLang!
    • BoxLang Cloud Servers
      • Microsoft Azure
      • Amazon Web Services
    • IDE & Tooling
      • BoxLang Debugger
        • MiniServer Debugging
        • CommandBox Debugging
      • BoxLang Compiler
      • CFML Feature Audit
      • CFML to BoxLang Transpiler
    • Runtime Configuration
      • Directives
      • Caches
      • Datasources
      • Experimental
      • Executors
      • Logging
      • Modules
      • Security
  • BoxLang Language
    • Program Structure
    • Syntax & Semantics
      • Comments
      • Variables
      • Variable Scopes
      • Operators
      • Null & Nothingness
      • Strings
      • Numbers
      • JSON
      • Arrays
      • Structures
      • Queries
      • Datasources
      • Conditionals
      • Attempts
      • Data Navigators
      • Exception Management
      • Code Locking
      • Closures => Context Aware
      • Lambdas -> Pure Functions
      • Includes
      • Threading
    • Classes & O.O.
      • Properties
      • Functions
      • Static Constructs
      • Final Constructs
      • Abstract Constructs
      • Interfaces
    • Reference
      • API Docs
      • Lexical Elements
        • Scopes and Constants
        • Keywords
        • Operators
        • Literals
        • Comments
        • Tokens
        • Semicolons
        • Identifiers
        • Packages and Imports
        • Java Interoperability
        • Errors
      • Types
        • array
        • class
        • date
        • datetime
        • file
        • numeric
        • query
        • stream
        • string
        • struct
        • xml
      • Built-in Functions
        • array
          • ArrayAppend
          • ArrayAvg
          • ArrayClear
          • ArrayContains
          • ArrayContainsNoCase
          • ArrayDelete
          • ArrayDeleteAt
          • ArrayDeleteNoCase
          • ArrayEach
          • ArrayEvery
          • ArrayFilter
          • ArrayFind
          • ArrayFindAll
          • ArrayFindAllNoCase
          • ArrayFindNoCase
          • ArrayFirst
          • ArrayGetMetadata
          • ArrayIndexExists
          • ArrayInsertAt
          • ArrayIsDefined
          • ArrayLast
          • ArrayMap
          • ArrayMax
          • ArrayMedian
          • ArrayMerge
          • ArrayMid
          • ArrayMin
          • ArrayNew
          • ArrayPop
          • ArrayPrepend
          • ArrayPush
          • ArrayRange
          • ArrayReduce
          • ArrayReduceRight
          • ArrayResize
          • ArrayReverse
          • ArraySet
          • ArrayShift
          • ArraySlice
          • ArraySome
          • ArraySort
          • ArraySplice
          • ArraySum
          • ArraySwap
          • ArrayToList
          • ArrayToStruct
          • ArrayUnshift
        • async
          • ExecutorGet
          • ExecutorHas
          • ExecutorList
          • ExecutorNew
          • ExecutorShutdown
          • ExecutorStatus
          • FutureNew
          • IsInThread
          • RunAsync
          • ThreadJoin
          • ThreadNew
          • ThreadTerminate
        • bifs
          • BoxLangBIFProxy
        • binary
          • BinaryDecode
          • BinaryEncode
          • BitAnd
          • BitMaskClear
          • BitMaskRead
          • BitMaskSet
          • BitNot
          • BitOr
          • bitShln
          • bitShrn
          • BitXor
        • cache
          • Cache
          • CacheFilter
          • CacheNames
          • CacheProviders
          • CacheService
        • cli
          • CLIExit
          • CLIGetArgs
          • CLIRead
        • conversion
          • DataNavigate
          • JSONDeserialize
          • JSONPrettify
          • JSONSerialize
          • LSParseNumber
          • ParseNumber
          • ToBase64
          • ToBinary
          • ToModifiable
          • ToNumeric
          • ToScript
          • ToString
          • ToUnmodifiable
        • decision
          • ArrayIsEmpty
          • Attempt
          • IsArray
          • IsBinary
          • IsBoolean
          • IsClosure
          • IsCustomFunction
          • IsDate
          • IsDateObject
          • IsDebugMode
          • IsDefined
          • IsEmpty
          • IsFileObject
          • IsIPv6
          • IsJSON
          • IsLeapYear
          • IsLocalHost
          • IsNull
          • IsNumeric
          • IsNumericDate
          • IsObject
          • IsQuery
          • IsSimpleValue
          • IsStruct
          • IsValid
          • IsXML
          • IsXmlAttribute
          • IsXMLDoc
          • IsXMLElem
          • IsXMLNode
          • IsXMLRoot
          • LSIsNumeric
          • structIsEmpty
        • encryption
          • Decrypt
          • Encrypt
          • EncryptBinary
          • GeneratePDBKDFKey
          • GenerateSecretKey
          • Hash
          • Hash40
          • Hmac
        • format
          • BooleanFormat
          • DecimalFormat
          • LSNumberFormat
          • NumberFormat
        • i18n
          • ClearLocale
          • CurrencyFormat
          • GetLocale
          • GetLocaleDisplayName
          • GetLocaleInfo
          • IsCurrency
          • LSCurrencyFormat
          • LSIsCurrency
          • LSParseCurrency
          • ParseCurrency
          • SetLocale
        • io
          • ContractPath
          • CreateTempDirectory
          • CreateTempFile
          • DirectoryCopy
          • DirectoryCreate
          • DirectoryDelete
          • DirectoryExists
          • DirectoryList
          • DirectoryMove
          • DirectoryRename
          • ExpandPath
          • FileAppend
          • FileClose
          • FileCopy
          • FileDelete
          • FileExists
          • FileGetMimeType
          • FileInfo
          • FileIsEOF
          • FileMove
          • FileOpen
          • FileRead
          • FileReadBinary
          • FileReadLine
          • FileSeek
          • FileSetAccessMode
          • FileSetAttribute
          • FileSetLastModified
          • FileSkipBytes
          • FileWrite
          • FileWriteLine
          • GetCanonicalPath
          • GetDirectoryFromPath
          • GetFileInfo
          • getTempFile
        • java
          • CreateDynamicProxy
        • jdbc
          • IsInTransaction
          • IsWithinTransaction
          • PreserveSingleQuotes
          • QueryExecute
          • TransactionCommit
          • TransactionRollback
          • TransactionSetSavepoint
        • list
          • GetToken
          • ListAppend
          • ListAvg
          • ListChangeDelims
          • ListCompact
          • ListContains
          • ListContainsNoCase
          • ListDeleteAt
          • ListEach
          • ListEvery
          • ListFilter
          • ListFind
          • ListFindNoCase
          • ListFirst
          • ListGetAt
          • ListIndexExists
          • ListInsertAt
          • ListItemTrim
          • ListLast
          • ListLen
          • ListMap
          • ListPrepend
          • ListQualify
          • ListReduceRight
          • ListRemoveDuplicates
          • ListRest
          • ListSetAt
          • ListSome
          • ListSort
          • ListToArray
          • ListTrim
          • ListValueCount
          • ListValueCountNoCase
        • math
          • Abs
          • Acos
          • Asin
          • Atn
          • Ceiling
          • Cos
          • DecrementValue
          • Exp
          • Fix
          • Floor
          • FormatBaseN
          • IncrementValue
          • InputBaseN
          • Int
          • Log
          • Log10
          • Max
          • Min
          • Pi
          • PrecisionEvaluate
          • Rand
          • Randomize
          • RandRange
          • Round
          • Sgn
          • Sin
          • Sqr
          • Tan
        • query
          • QueryAddColumn
          • QueryAddRow
          • QueryAppend
          • QueryClear
          • QueryColumnArray
          • QueryColumnCount
          • QueryColumnData
          • QueryColumnExists
          • QueryColumnList
          • QueryCurrentRow
          • QueryDeleteColumn
          • QueryDeleteRow
          • QueryEach
          • QueryEvery
          • QueryFilter
          • QueryGetCell
          • QueryGetResult
          • QueryInsertAt
          • QueryKeyExists
          • QueryMap
          • QueryNew
          • QueryPrepend
          • QueryRecordCount
          • QueryReduce
          • QueryRegisterFunction
          • QueryReverse
          • QueryRowData
          • QueryRowSwap
          • QuerySetCell
          • QuerySetRow
          • QuerySlice
          • QuerySome
          • QuerySort
        • string
          • Ascii
          • CamelCase
          • Char
          • CharsetDecode
          • CharsetEncode
          • Compare
          • CompareNoCase
          • Find
          • FindNoCase
          • FindOneOf
          • Insert
          • JSStringFormat
          • KebabCase
          • LCase
          • Left
          • ListReduce
          • LJustify
          • LTrim
          • Mid
          • ParagraphFormat
          • PascalCase
          • QueryStringToStruct
          • ReEscape
          • ReFind
          • reFindNoCase
          • ReMatch
          • reMatchNoCase
          • RemoveChars
          • RepeatString
          • Replace
          • ReplaceList
          • ReplaceListNoCase
          • ReplaceNoCase
          • ReReplace
          • reReplaceNoCase
          • Reverse
          • Right
          • RJustify
          • RTrim
          • Slugify
          • SnakeCase
          • SpanExcluding
          • SpanIncluding
          • SQLPrettify
          • StringBind
          • StringEach
          • StringEvery
          • StringFilter
          • StringMap
          • StringReduce
          • StringReduceRight
          • StringSome
          • StringSort
          • StripCR
          • Trim
          • TrueFalseFormat
          • UCase
          • UCFirst
          • Val
          • Wrap
          • YesNoFormat
        • struct
          • StructAppend
          • StructClear
          • StructCopy
          • StructDelete
          • StructEach
          • StructEquals
          • StructEvery
          • StructFilter
          • StructFind
          • StructFindKey
          • StructFindValue
          • StructGet
          • StructGetMetadata
          • StructInsert
          • StructIsCaseSensitive
          • StructIsOrdered
          • StructKeyArray
          • StructKeyExists
          • StructKeyList
          • StructKeyTranslate
          • StructMap
          • StructNew
          • StructReduce
          • StructSome
          • StructSort
          • StructToQueryString
          • StructToSorted
          • StructUpdate
          • StructValueArray
        • system
          • ApplicationRestart
          • ApplicationStartTime
          • ApplicationStop
          • BoxAnnounce
          • BoxAnnounceAsync
          • BoxRegisterInterceptionPoints
          • BoxRegisterInterceptor
          • BoxRegisterRequestInterceptor
          • CallStackGet
          • CreateGUID
          • CreateObject
          • CreateUUID
          • DE
          • DebugBoxContexts
          • Dump
          • Duplicate
          • echo
          • EncodeForHTML
          • GetApplicationMetadata
          • GetBaseTagData
          • GetBaseTagList
          • GetBaseTemplatePath
          • GetBoxContext
          • GetBoxRuntime
          • GetBoxVersionInfo
          • GetClassMetadata
          • GetComponentList
          • GetContextRoot
          • GetCurrentTemplatePath
          • GetFileFromPath
          • GetFunctionCalledName
          • GetFunctionList
          • GetModuleInfo
          • GetModuleList
          • GetRequestClassLoader
          • GetSemver
          • GetSystemSetting
          • GetTempDirectory
          • GetTickCount
          • htmlEditFormat
          • IIF
          • Invoke
          • IsInstanceOf
          • JavaCast
          • ObjectDeserialize
          • ObjectSerialize
          • PagePoolClear
          • Print
          • Println
          • RunThreadInContext
          • SessionInvalidate
          • SessionRotate
          • SessionStartTime
          • Sleep
          • SystemCacheClear
          • SystemExecute
          • SystemOutput
          • Throw
          • Trace
          • URLDecode
          • URLEncodedFormat
          • writeDump
          • WriteLog
          • WriteOutput
        • temporal
          • ClearTimezone
          • CreateDate
          • CreateDateTime
          • CreateODBCDate
          • CreateODBCDateTime
          • CreateODBCTime
          • CreateTime
          • CreateTimeSpan
          • DateAdd
          • DateCompare
          • DateConvert
          • DateDiff
          • DateFormat
          • DatePart
          • DateTimeFormat
          • Day
          • DayOfWeek
          • DayOfWeekAsString
          • DayOfWeekShortAsString
          • DayOfYear
          • DaysInMonth
          • DaysInYear
          • FirstDayOfMonth
          • GetNumericDate
          • GetTime
          • GetTimezone
          • GetTimezoneInfo
          • Hour
          • Millisecond
          • Minute
          • Month
          • MonthAsString
          • MonthShortAsString
          • Nanosecond
          • Now
          • Offset
          • ParseDateTime
          • Quarter
          • Second
          • SetTimezone
          • TimeFormat
          • Week
          • Year
        • type
          • ArrayLen
          • GetMetaData
          • Len
          • NullValue
          • StringLen
          • StructCount
        • web
          • HtmlHead
          • GetHTTPTimeString
          • GetHTTPRequestData
          • HtmlFooter
          • SetEncoding
          • Forward
          • Location
          • GetPageContext
          • FileUpload
          • FileUploadAll
        • xml
          • XMLChildPos
          • XMLElemNew
          • XMLFormat
          • XMLGetNodeType
          • XMLNew
          • XMLParse
          • XMLSearch
          • XMLTransform
          • XMLValidate
        • zip
          • Compress
          • Extract
          • IsZipFile
      • Components
        • async
          • Thread
        • cache
          • Cache
        • debug
          • Stopwatch
          • Timer
        • io
          • Directory
          • File
        • jdbc
          • DBInfo
          • ProcParam
          • ProcResult
          • Query
          • QueryParam
          • StoredProc
          • Transaction
        • net
          • HTTP
          • HTTPParam
        • system
          • Abort
          • Application
          • Associate
          • Component
          • Dump
          • Execute
          • Exit
          • Flush
          • Include
          • Invoke
          • InvokeArgument
          • Lock
          • Log
          • Loop
          • Object
          • Output
          • Param
          • ProcessingDirective
          • SaveContent
          • Setting
          • Silent
          • Sleep
          • Throw
          • Trace
        • web
          • HtmlHead
          • HtmlFooter
          • Location
          • Cookie
          • Header
          • Content
        • xml
          • XML
        • zip
          • Zip
      • Exceptions
  • BoxLang Framework
    • Application.bx
    • Asynchronous Programming
    • File Handling
    • Interceptors
      • Core Interception Points
        • Application Events
        • Cache Service Events
        • Cache Provider Events
        • Cache Object Store Events
        • Datasource Service Events
        • Dump Events
        • Dynamic Object Events
        • Function Invocations
        • HTTP Events
        • Life-cycle Events
        • Logging Events
        • Module Events
        • Module Service Events
        • Object Marshalling Events
        • Query Invocations
        • Runtime Events
        • Request Context Events
        • Scheduler Events
        • Scheduler Service Events
        • Template Invocations
        • Transaction Events
      • Request Interception Points
    • HTTP/S Calls
    • Java Interop
    • JDBC Transactions
    • Modules
      • AI
      • Compat CFML
        • Reference
          • Types
            • array
            • datetime
            • numeric
            • string
            • struct
          • Built-in Functions
            • cache
              • CacheCount
              • CacheGetAsAttempt
              • CacheRegionRemove
              • CacheRemoveAll
              • CachePut
              • CacheRegionExists
              • CacheGetSession
              • CacheGetEngineProperties
              • CacheGet
              • CacheGetDefaultCacheName
              • CacheGetProperties
              • CacheSetProperties
              • CacheGetAllIds
              • CacheIdExists
              • cacheKeyExists
              • CacheRemove
              • cacheDelete
              • CacheGetAll
              • CacheGetMetadata
              • CacheGetOrFail
              • CacheClear
              • CacheRegionNew
            • conversion
              • JSONDeserialize
            • encryption
              • Hash
              • Hash40
            • format
              • HTMLCodeFormat
              • DollarFormat
            • struct
              • DeleteClientVariable
            • system
              • Throw
              • ObjectSave
              • GetFunctionData
              • GetComponentMetadata
              • GetVariable
              • GetTagData
              • GetClientVariablesList
              • GetContextRoot
              • ObjectLoad
              • SetVariable
            • temporal
              • LSWeek
              • LSDayOfWeek
              • LSIsDate
              • DateCompare
              • GetHTTPTimestring
              • LSDateTimeFormat
              • LSDateFormat
              • LSTimeFormat
              • DayOfWeekAsString
              • DayOfWeekShortAsString
              • MonthAsString
              • MonthShortAsString
              • ToLegacyDate
              • createDate
              • LSParseDateTime
              • DateTimeFormat
              • DateFormat
              • TimeFormat
            • type
              • GetMetaData
          • Components
            • net
              • HTTP
      • CSRF
      • ESAPI
      • Evaluating Code
      • FTP
      • Image Manipulation
      • INI Files
      • JDBC
      • Jython
      • Mail
      • Markdown
      • ORM
      • OSHI - Operating System + Hardware
      • Password Encryption
      • PDF
      • Redis
      • UI Forms
      • WDDX
      • Web Support
      • Yaml
  • Extra Credit
    • MVC
    • Dependency Injection
Powered by GitBook
LogoLogo

Social Media

  • X
  • FaceBook
  • LinkedIn
  • YouTube

Bug Tracking

  • Runtimes
  • IDE
  • Modules

Support

  • Professional
  • Community
  • Slack

Copyright & Register Trademark by Ortus Solutions, Corp

On this page

Was this helpful?

Edit on GitHub
Export as PDF

Last updated 6 months ago

Was this helpful?

A datasource is a named connection to a specific database with specified credentials. You can define a datasource in one of three locations:

  1. For web applications,

The datasource is then used to control the database's connection pool and allow the BoxLang engine to execute JDBC calls against it.

What Database Vendors Are Supported?

The following database vendors are supported and available:

Each database we support comes with an installable BoxLang module which either

  1. provides the necessary client dependencies for making JDBC connections to a running database server (MySQL, Postgres, etc.)

  2. OR contains the database vendor itself, as in the case of Apache Derby or HyperSQL, which are both in-memory database.

To use any of these databases you'll need to install its BoxLang module to support JDBC connections to that datasource.

Make Sure to Specify a Driver

The datasource configuration struct should be defined exactly the same whether you are using an inline, ad-hoc datasource or configuring a datasource in your boxlang.json or Application.bx. Make sure you have a "driver" key defined OR the driver clearly denoted in the JDBC url:

Defining Datasources In boxlang.json

You can define a datasource at the BoxLang runtime level by placing it in your boxlang.json:

Defining Datasources In Application.bx

For web runtimes, you can also define the datasources in the Application.bx, which is sometimes our preferred approach as the connections are versioned controlled and more visible than in the admin. You will do this by defining a struct called this.datasources. Each key will be the name of the datasource to register and the value of each key a struct of configuration information for the datasource. However, we recommend that you setup environment variables in order to NOT store your passwords in plain-text in your source code.

For the inline approach, you will use the struct definition, as you see in the Application.bx above and pass it into the bx:query or queryexecute call.

Defining Inline Datasources

Finally, for smaller or simpler applications with few queries, you may find it useful to define your datasource at query time. So instead of giving the name of the datasource, it can be a struct definition of the datasource you want to connect to:

Default Datasource

You can also define a default datasource to allow you to omit the datasource completely from query calls.

To do this, you'll need to define a default datasource in one of two locations:

  1. In your BoxLang runtime's boxlang.json config file via the defaultDatasource key

  2. or, for web server runtimes, in a this.datasource variable in your Application.bx file

Defining a default datasource via boxlang.json

Defining a default datasource via Application.bx

Portable Datasources

  • CF Mappings

  • Data sources

  • Mail servers

  • Request, session, or application timeouts

  • Licensing information

  • Passwords

  • Template caching settings

  • Basically any settings in the web based administrator

You can easily place a .cfconfig.json in the web root of your project, and if you start up a CommandBox server on any BoxLang engine, CFConfig will transfer the configuration to the engine's innards:

Datasource Configuration

All Configuration Properties

Datasource Connection Pooling

  • maxConnections

  • minConnections

  • connectionTimeout

  • idleTimeout

  • maxLifetime

  • keepaliveTime

Pool Statistics

BoxLang offers a number of pool statistics which can be retrieved from the datasource object. To do this, first find your datasource name from the list of registered datasources:

Next, retrieve the datasource by its unique datasource name, and call .getPoolStats() on the result:

This returns a struct of pool metadata including the following keys:

  • pendingThreads

  • idleConnections

  • totalConnections

  • activeConnections

  • maxConnections

  • minConnections

Find out what datasources you have defined by dumping out this getBoxContext().getRuntime().getDatasourceService().getNames()

Note the use of BoxLang's environment variable replacement syntax for the datasource properties: ${env.MYSQL_HOST:localhost}. See for more info.

You can also make your data sources portable from application to application or BoxLang engine to engine by using our project. CFConfig allows you to manage almost every setting that shows up in the web administrator, but instead of logging into a web interface, you can manage it from the command line by hand or as part of a scripted server setup. You can seamlessly transfer config for all the following:

Property
Type
Default
Description

In addition to the above properties, you can include any you'd like in your datasource configuration:

BoxLang uses under the hood for connection pooling. Each datasource gets a dedicated connection pool. Use these configuration properties to adjust the pool size and behavior:

this.datasources[ "testDB" ] = {
	"driver": "mysql",
	// OR:
	"url" : "jdbc:mysql://localhost:3306/test"
};
boxlang.json
  "datasources": {
      "theDerbyDB": {
      	"driver": "derby",
    	"connectionString": "jdbc:derby:memory:testDB;create=true"
      },
      "theMysqlDB": {
      	"driver": "mysql",
        "host": "${env.MYSQL_HOST:localhost}",
        "port": "${env.MYSQL_PORT:3306}",
        "database": "${env.MYSQL_DATABASE:myDB}",
        "username": "${env.MYSQL_USERNAME:root}",
        "password": "${env.MYSQL_PASSWORD}"
      }
  },
Application.bx
class{
    this.datasources = {
        // Driver Approach
        mysql = {
            database : "mysql",
            host : "localhost",
            port : "3306",
            driver : "MySQL",
            username : "root",
            password : "mysql",
            options : value
        },
        // URL approach
        mysql2 = {
            driver : "mysql",
            url : "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useLegacyDatetimeCode=true",
            username : "",
            password : ""
        },
        // Shorthand Approach
        myDSN = {
            class : "com.mysql.jdbc.Driver",
            connectionString : "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useLegacyDatetimeCode=true",
            username : "",
            password : ""
        },
        // Long Approach
        myDSN = {
            type : "mysql",
            database : "mysql",
            host : "localhost",
            port : "3306",
            username : "",
            password : ""
        }
    };
}
queryExecute(
  "SELECT * FROM Employees WHERE empid = ? AND country = ?", // sql
  [ 1, "USA" ], // params
  { // options
    datasource : {
      "driver": "mysql",
      "host": "${env.MYSQL_HOST:localhost}",
      "port": "${env.MYSQL_PORT:3306}",
      "database": "${env.MYSQL_DATABASE:myDB}",
      "username": "${env.MYSQL_USERNAME:root}",
      "password": "${env.MYSQL_PASSWORD}"
    }
  }
)
boxlang.json
   "defaultDatasource: {
      "driver": "mysql",
       "host": "${env.MYSQL_HOST:localhost}",
       "port": "${env.MYSQL_PORT:3306}",
       "database": "${env.MYSQL_DATABASE:myDB}",
       "username": "${env.MYSQL_USERNAME:root}",
       "password": "${env.MYSQL_PASSWORD}"
    },
   "datasources": {
      // You can still define additional datasources here! You're not limited to the default datasource
   },
Application.bx
class{
    this.name = "myApp";

    // Default Datasource Name
    this.datasource = "pantry";

}
.cfconfig.json
{
    "requestTimeoutEnabled":true,
    "whitespaceManagement":"white-space-pref",
    "requestTimeout":"0,0,5,0",
    "cacheDefaultObject":"coldbox",
    "caches":{
        "coldbox":{
            "storage":"true",
            "type":"RAM",
            "custom":{
                "timeToIdleSeconds":"1800",
                "timeToLiveSeconds":"3600"
            },
            "readOnly":"false"
        }
    },
    "datasources" : {
         "coldbox":{
             "host":"${DB_HOST}",
             "dbdriver":"${DB_DRIVER}",
             "database":"${DB_DATABASE}",
             "dsn":"jdbc:mysql://{host}:{port}/{database}",
             "custom":"useUnicode=true&characterEncoding=UTF-8&useLegacyDatetimeCode=true&autoReconnect=true",
             "port":"${DB_PORT}",
             "class":"${DB_CLASS}",
             "username":"${DB_USER}",
             "password":"${DB_PASSWORD}",
             "connectionLimit":"100",
             "connectionTimeout":"1"
         }
    }
}
"coldbox":{
    ...
   "connectionInitSql":"custom SQL statement to run on connection initialize...",
}
// get array of unique datasource names for all apps
writeDump( getBoxContext().getRuntime().getDatasourceService().getNames() );
writeDump( getBoxContext().getRuntime().getDatasourceService().get( "app_12345_my_Datasource_Name" ).getPoolStats() );
  1. BoxLang Language
  2. Syntax & Semantics

Datasources

PreviousQueriesNextConditionals
  • What Database Vendors Are Supported?
  • Make Sure to Specify a Driver
  • Defining Datasources In boxlang.json
  • Defining Datasources In Application.bx
  • Defining Inline Datasources
  • Default Datasource
  • Defining a default datasource via boxlang.json
  • Defining a default datasource via Application.bx
  • Portable Datasources
  • Datasource Configuration
  • All Configuration Properties
  • Datasource Connection Pooling
  • Pool Statistics
CFConfig
Hikari configuration property
HikariCP
Apache Derby
HyperSQL
MariaDB
Microsoft SQL Server
MySQL
Oracle
PostgreSQL
At the boxlang runtime level via your boxlang.json config file
in your Application.bx via this.datasources
Inline, at query time, via the queryExecute() BIF, query or dbInfo component, etc

driver

String

dbdriver

String

Alias for driver. Deprecated

class

String

Specify a custom or specific class to use as the database driver. Not recommended - use the correct driver instead.

custom

Struct

Struct of custom properties.

username

String

Database connection username.

password

String

Database connection password.

maxConnections

Integer

10

The maximum number of connections. Alias for Hikari's maximumPoolSize

minConnections

Integer

10

The minimum number of connections. Alias for Hikari's minimumIdle

connectionTimeout

Integer

1

Maximum time to wait for a successful connection, in seconds.

idleTimeout

Integer

600

The maximum number of idle time in seconds (10 Minutes = 600). Refers to the maximum amount of time a connection can remain idle in the pool before it is eligible for eviction.

maxLifetime

Integer

1800

This property controls the maximum lifetime of a connection in the pool. An in-use connection will never be retired, only when it is closed will it then be removed. 30 minutes by default = 1800 seconds.

keepaliveTime

Integer

600

This property controls how frequently HikariCP will attempt to keep a connection alive, in order to prevent it from being timed out by the database or network infrastructure. 10 Minutes = 600 seconds.

autoCommit

Boolean

true

The default auto-commit state of connections created by this pool.

registerMbeans

Boolean

true

Register mbeans for JMX connection monitoring support.

Datasource driver to use. Corresponds with the boxlang JDBC driver module - see

What Database Vendors Are Supported?
Environment Variable Substitution
Command OverviewCFConfig Documentation
Logo