How to create a dsn-less database connection in Coldfusion - page 3

Author: Steven Neiland
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.

Step 6: Close the Connection

Finally we need to remember to close the connection to the database to free up resources.

<!--- Close the connection --->
<cfset connection.Close()>

Complete Code

So there we have it. A simple way to connect to a database from Coldfusion without creating a datasource. For reference the complete code is below, you will obviously need to put in error handling.

<!--- Load the database driver using java class loader --->
<cfset classLoader = createObject("java", "java.lang.Class")>
<cfset classLoader.forName("com.mysql.jdbc.Driver")>

<!--- Create a driver manager instance --->
<cfset driverManager = createObject("java","java.sql.DriverManager")>

<!--- Create the connection to the DB --->
<cfset connection = driverManager.getConnection(
"jdbc:mysql://localhost:3306/demodb?user=demouser&password=demopass")>


<!---Create a connection statement and run our query string --->
<cfset statement = connection.createStatement()>      
<cfset resultSet = statement.ExecuteQuery("SELECT * FROM testtable")>

<!---Convert the resultset into a coldfusion query object --->
<cfset queryObj = createObject("java", "coldfusion.sql.QueryTable").init(resultSet)>

<!--- Close the connection --->
<cfset connection.Close()>
1 2 3

Reader Comments

  • Please keep comments on-topic.
  • Please do not post unrelated questions or large chunks of code.
  • Please do not engage in flaming/abusive behaviour.
  • Comments that contain advertisments or appear to be created for the purpose of link building, will not be published.

Archives Blog Listing