I've done this in two ways in scripts that I've written: the first is to just instantiate a WeBWorK database object in my script, and the second is the way you suggest, just querying the WeBWorK database directly.
There are a number of examples of how to set up the first in the bin directory of the WeBWorK installation (e.g., addcourse and delcourse). There are some others on the wiki: http://webwork.maa.org/wiki/Contributed_Admin_Scripts_%28Large_Installations%29 . The basic idea is that one needs to set the library path so that one can load a CourseEnvironment and the database. If that doesn't make sense we can discuss it further.
The second way is less robust (as the database design changes one has to change ones script).
Is that helpful?
WeBWorK Main Forum
How access Webwork student data outside of Webwork? Use SQL command to access Webwork database?
This forum has a limit to the number of forum postings you can make in a given time period - this is currently set at 10 posting(s) in 1 day