Database Operations with 
JDBC and J/Link

Initialization

Off[ General::spell];
Off[General::spell1];

Load J/Link and Launch Java

<< JLink`

InstallJava[]

Load the JDBC/ODBC driver.

JavaNew[ "sun.jdbc.odbc.JdbcOdbcDriver"]

Load the driver manager (to call the getConnection static method).

LoadClass["java.sql.DriverManager"]

Open Database Connection

Done with J/Link style calls,  the Java code would be very similar.

con = 
      java`sql`DriverManager`getConnection[
"Jdbc:Odbc:\
ComputeServer",  "",  ""]

Execute Query

Here we will prepare and execute a statement, get all the username from the Users table.

st = con@prepareStatement["SELECT username FROM Users "]

rs = st@executeQuery[]

The result of the executeQuery is a ResultSet object.  This can be iterated over to extract results.  

Iterate over the records and pull out values from the columns. 

rs@next[]

rs@getString[1]

Make a Mathematica Function

Now we can put everything into a Mathematica function.  It is not written for efficiency.

ExecuteQuery[ con_,name_,table_]:=
	JavaBlock[
		Module[ {st, res, ef = {}},
			st = con@prepareStatement[
				"SELECT "<> name <> " FROM " <> table] ;
			res = st@executeQuery[] ;
			While[ res@next[], ef = Append[ef,res@getString[1]]] ;
			ef
			]
		]

Now we can use the function.

ExecuteQuery[con,"username","Users"]