Thursday, July 2, 2009

DSN-Less Database Connection to MySQL in Coldfusion

Have not tried this myself yet, but wanted to drop it here so we can play with it in the future.

A DSN-less connection is made completely through the code, without the need for configuring anything within the ColdFusion Administrator. All of the information for the connection is specified within the code. This includes the driver, servername, databasename, username and password.


To make a DSN-less connection to a MySQL database, the following code snippet can be used:



<cfscript>

classLoader = createObject("java", "java.lang.Class");
classLoader.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dm = createObject("java","java.sql.DriverManager");

con = dm.getConnection("jdbc:odbc:DRIVER={MySQL ODBC 3.51 Driver}; SERVER=server; PORT=3306;
DATABASE=database; USER=username; PASSWORD=password;OPTION=3;");


st = con.createStatement();
rs = st.ExecuteQuery("Select * FROM table");
q = createObject("java", "coldfusion.sql.QueryTable").init(rs);

//the query is stored in the variable q


</cfscript>

No comments:

Post a Comment