Published:
Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.
Coldfusion datasources are great. Having one single point where you can setup a named connection to a given database complete host, ports, username and passwords makes life so much easier than other languages. However what if you need to create a temporary connection to an outside database but you don't have access to the Coldfusion administrator?
Solution: Roll Our Own Connection
Since Coldfusion is built on java we know that it has a library of drivers which it uses to connect to different databases. All we need to do is jump down into java to access these drivers and create our own connection to the database outside of the CF admin.
Note: For this example I am going to create a JDBC connection to a demo MySQL5 Database on localhost.
Step 1: List Available Drivers
First lets check if our desired driver exists. While this is not strictly necessary if you know that your driver already exists in Coldfusion it doesn't hurt to know how to get the data. In addition this step will tell us what arguments we need to supply to the connection methods and in what order.
To do this we create an instance of coldfusion's service factory and dump the results of the getDrivers() method.
<cfset factory = createObject("java", "coldfusion.server.ServiceFactory") />
<cfdump var="#factory.dataSourceService.getDrivers()#">
A quick look at the structure should tell you if your driver is available, plus the connection string format it expects.
Step 2: Load the Driver Using the Java Class Loader
In this example I am connection to a MySQL5 database, and according to the structure from the above cfdump the relevant driver is "com.mysql.jdbc.Driver". So to load this driver into memory we create a classloader object and call the forName() method specifying the driver.
<!--- Load the database driver using java class loader --->
<cfset classLoader = createObject("java", "java.lang.Class")>
<cfset classLoader.forName("com.mysql.jdbc.Driver")>
Reader Comments